Webpack 的output中 path与publicPath

2020-04-04  本文已影响0人  月下吴刚_c8c7
  1. output 中的 path 和 publicPath
publicPath大白话:

publicPath取决于根目录path的位置,因为打包的文件都在path目录了,这些文件的引用都是基于该目录的。假设path为public,引用的图片路径是'./img.png',如果publicPath为'/',图片显示不了,因为图片都打包放在了dist中,那么你就要把publicPath设置为”/dist”。

  1. 举个栗子:

假设你将这个工程部署在服务器 http://server/
通过将output.publicPath设置为/assets/,这个工程将会在http://server/assets/找到webpack资源。
在这种前提下,所有与webpack相关的路径都会被重写成以/assets/开头。

src="picture.jpg" Re-writes ➡ src="/assets/picture.jpg"
Accessed by: (http://server/assets/picture.jpg)
src="/img/picture.jpg" Re-writes ➡ src="/assets/img/picture.jpg"
Accessed by: (http://server/assets/img/picture.jpg)

  1. devServer 中的publicPath

此路径下的打包文件可在浏览器中访问。
假设服务器运行在 http://localhost:8080 并且 output.filename 被设置为 bundle.js。默认 devServer.publicPath 是 '/',所以你的包(bundle)可以通过http://localhost:8080/bundle.js 访问。
修改 devServer.publicPath,将 bundle 放在指定目录下:

module.exports = {
  //...
  devServer: {
    publicPath: '/assets/'  // 现在可以通过 http://localhost:8080/assets/bundle.js 访问 bundle。
  }
};  

dev 时 在内存中的路径,大多时候,output.publicPath和devserver.publicPath 保持一致。

最后

如果你在用style-loader或者css sourceMap,你就需要设置publicPath。把它设置成服务器地址的绝对路径,比如http://server/assets/,这样资源可以被正确加载。

上一篇 下一篇

猜你喜欢

热点阅读