我们知道output
中的path
的作用是打包后文件输出的目录:比如静态资源的js、css
等输出,常见的会设置为dist、build文件夹
等;
output
中还有一个publicPath
属性,该属性是指定index.html
文件打包引用的一个基本路径:
./
,根据./bundle.js
相对路径去查找资源;举例:
module.exports = { mode: "development", entry: "./src/index.js", output: { filename: "bundle.js", // 打包后的文件的输出目录 path: path.resolve(__dirname, "./build"), // 在打包之后的静态资源前面进行一个路径的拼接: publicPath: "./" }, }
打包后:
devServer中也有一个publicPath的属性,该属性是指定开发环境webpack serve下开启本地服务所在的文件夹:
/
,也就是我们直接访问端口即可访问其中的资源 http://localhost:8080;举例:
module.exports = { // watch: true, mode: "development", entry: "./src/index.js", output: { filename: "bundle.js", // 打包后的文件的输出目录 path: path.resolve(__dirname, "./build"), // 在打包之后的静态资源前面进行一个路径的拼接 publicPath: "/abc" //和下方publicPath设置一样 }, // 专门为webpack-dev-server // devServer为开发过程中, 开启一个本地服务 devServer: { compress: true, //文件压缩启用 [gzip compression] publicPath: "/abc", }, }
官方提到: devServer.publicPath 与 output.publicPath相同
打包后:
注意:上方devServer设置/abc后,我们其中的bundle.js通过 http://localhost:8080/bundle.js是无法访问的,报错如下:
所以devServer.publicPath 与 output.publicPath设置要相同!