webpack打包中publicPath的采坑
在使用webpack打包过程中有多处使用publicPath导致理解出现误差,特写此文章已做记录。
publicPath是一个在很多的loader中都有的一个配置,它是一个静态文件的发布目录,在output中可以进行默认的publicPath设置,也可以在对应的loader中分别设置。
output中设置的对应为webpack_public_path这个内置变量。
常用的设置:
1.在“file-loader"中的publicPath,为你的文件配置自定义 public 发布目录,默认值为output.publicPath。
以常用图片为例:
不设置“file-loader"中publicPath则文件打包后的路径为output.publicPath+fileLoader.outputPath+name.ext设置后图片路径为fileLoader.publicPath+name.ext详细file-loader的使用可点击查看
{
test: /\.(png|svg|jpg|gif)$/,
use: [
// 'file-loader'
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'images/',
publicPath:'../images/',
}
}
]
}
2.在webpack-dev-server中使用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 访问。devServer.publicPath 和 output.publicPath 一样被推荐。
在dev模式中设置了publicPath后访问路径为http://localhost:8080/{publicPath}/{文件相对路径} 此路径下将会进行页面的实时刷新。但是仍然可以访问http://localhost:8080/{文件相对路径}这个路径将不会做任何的刷新动作,在控制台看到Compiled successfully.但页面没有任何刷新可以检测一下路径是否有错误。
devServer: {
contentBase: './dist',
publicPath:'/assets/'
},
只设置了output默认的publicPath会出现dev模式和prodction模式的打包后表现不一致问题,dev模式一切正常但是production模式中图片地址无法访问的情况,建议每个loader单独进行设置。
最后贴出我的使用版本
"css-loader": "^5.0.1",
"file-loader": "^6.2.0",
"style-loader": "^2.0.0",
"uglifyjs-webpack-plugin": "^2.2.0",
"webpack": "^4.44.2",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0",
"webpack-merge": "^5.3.0"