了解webpack中各种publicPath的含意

output中的publicPath

  • type: function | string

对于按需加载(on-demand-load)或加载内部资源(external resources)(如图片、文件等)来说,output.publicPath 是很重要的选项。如果指定了一个谬误的值,则在加载这些资源时会收到 404 谬误。

htmlWebpackPlugin的publicPatch

  • type: string
  • default: 'auto'

用户<script><link>的publicPath

devServer的publicPath

其实,咱们常常容易搞混的就是output的publicPath和deveServer的publicPatch

在开发阶段,咱们借用 devServer 启动一个开发服务器进行开发,这里也会配置一个 publicPath,这里的 publicPath 门路下的打包文件能够在浏览器中拜访。而动态资源依然应用 output.publicPath。

webpack-dev-server 打包的内容是放在内存中的,这些打包后的资源对外的的根目录就是 publicPath,换句话说,动态资源在内存中的门路都是以 publicPath 为准的。

确保 devServer.publicPath 始终以正斜杠结尾和结尾

从文档中,咱们能够看到 倡议 devServer.publicPath 与 output.publicPath 雷同,这是为啥?

因为平时咱们我的项目生成 html 文件都是应用 webpack 插件 html-webpack-plugin 生成,其中波及到 js、css、img 的动态文件的门路解决,html-webpack-plugin 是基于 output.publicPath 生成最终拜访链接的。

如果 webpack-dev-server 的 publicPath 和 output.publicPath 不统一,在应用 html-webpack-plugin 可能会导致援用动态资源失败,因为在 webpack-dev-server 中生成 html 时,html-webpack-plugin 依然以 output.publicPath 援用动态资源,和 webpack-dev-server 的提供的资源拜访门路不统一,从而无奈失常拜访。

vue-cli的publicPath

  • Type: string
  • Default: '/'
用法和 webpack 自身的 output.publicPath 统一,然而 Vue CLI 在一些其余中央也须要用到这个值,所以请始终应用 publicPath 而不要间接批改 webpack 的 output.publicPath。

这个值也能够被设置为空字符串 ('') 或是相对路径 ('./'),这样所有的资源都会被链接为相对路径,这样打进去的包能够被部署在任意门路,也能够用在相似 Cordova hybrid 利用的文件系统中。

绝对 publicPath 的限度

相对路径的 publicPath 有一些应用上的限度。在以下状况下,该当防止应用绝对 publicPath:

当应用基于 HTML5 history.pushState 的路由时;

当应用 pages 选项构建多页面利用时。

参考文章

  • output的publicpath和devServer的publicpath有什么关系
  • webpack的path、publicPath和 devServer 的publicPath、contentBase