assetsPublicPath

assetsPublicPath 相关配置

  • 当打包之后页面空白,字体图标和 mock 数据无法正常加载时,可能是 assetsPublicPath:’/‘的问题,先来了解一下配置属性的基本含义
1
2
3
4
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: './',

说明:

  • index: 模板
  • assetRoot: 打包后文件要存放的路径
  • assetsSubDirectory: 除了 index.html 之外的静态资源要存放的路径,
  • assetsPublicPath: 代表打包后,index.html 里面引用资源的的相对地址
1
2
3
4
5
6
7
8
9
index: path.resolve(__dirname, '../dist/index.html'), // Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: './assets/',
assetsPublicPath: './hello/',

打包后为
<script type="text/javascript" src="./hello/assets/js/manifest.js"></script>
<script type="text/javascript" src="./hello/assets/js/vendor.js"></script>
<script type="text/javascript" src="./hello/assets/js/app.js"></script>

所以可以说明

  • assetsRoot : 在当前目录的上一级的 dist 目录下输出资源文件
  • assetsSubDirectory: 把所有的静态资源打包到 dist 下的 assets 文件夹下
  • assetsPublicPath :代表生成的 index.html 文件,里面引入资源时,路径前面要加上 ./hello/,也就是 assetsPublicPath 的值

由此可见 ,我们可以直接设置 assetsPublicPath 为绝对路径,比如自己的线上路径前缀https://www.yourdomain.com/,则打包后的路径,全部会加上这个前缀,如果配置 package.json 的一些参数,就可以放心的把自己 html 里面的内容复制出来,放在任何地方都可以用了(前提是资源要先上线)


此外,线上发布的时候一般都会使用 nginx 反向代理,所以使用./是最靠谱的,但是 vue-cli dev 中的 assetsPublicPath 不能配置成”./“,而 build 中的却可以配置,并可以正常访问,虽然不影响发布但是影响开发效率。

解决方法

可以将 webpack.dev.conf.js 中的 publicPath 的值改成 “/“ 就行了

原因分析

  • publicPath 总是以斜杠(/)开头和结尾,所以 publicPath 不能配置为./ 所以访问时会报错
  • devServer.publicPath 路径下的打包文件可在浏览器中访问。假设服务器运行在 http://localhost:8080 并且 output.filename 被设置为 bundle.js。默认 publicPath 是 “/“,所以你的包(bundle)可以通过 http://localhost:8080/bundle.js 访问。

可以修改 publicPath,将 bundle 放在一个目录:publicPath:”/assets/“ 你的包现在可以通过 http://localhost:8080/assets/bundle.js 访问。

确保 publicPath 总是以斜杠(/)开头和结尾。也可以使用一个完整的 URL。这是模块热替换所必需的。 这里是重点

publicPath: “http://localhost:8080/assets/”

bundle 可以通过 http://localhost:8080/assets/bundle.js 访问。


参考链接:https://juejin.im/post/5bd9838df265da393c06033a

https://blog.csdn.net/isyoungboy/article/details/84350256

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2018-2020 Jee
  • Visitors: | Views:

如果您觉得此文章帮助到了您,请作者喝杯咖啡吧~

支付宝
微信