webpack配置中的path、publicPath和contentBase

 

output中的publicPath用于给生成的静态资源路径添加前缀,也就是会在打包生成的html文件里面引用资源路径中添加前缀。

当定义了output.publicPath值

 webpack配置中的path、publicPath和contentBase

webpack配置中的path、publicPath和contentBase

 webpack配置中的path、publicPath和contentBase

 webpack配置中的path、publicPath和contentBase

 如上图所示资源的路径加上了publicPath定义的前缀。并且output的publicPath影响到了使用devServer在打包生成的静态文件的位置,所以访问localhost:8080时失败。

 

devServer里面的publicPath表示的是此路径下的打包文件可在浏览器中访问,若是devServer里面的publicPath没有设置,则会认为是output里面设置的publicPath的值。

其内部实现是使用的express.static()中间件函数,例如 app.use('/public', express.static('contentBase')), '/public' 就相当于 devServer中设置的publicPath,'contentBase'就相当于devServer中设置的contentBase,这样当浏览器使用public路径访问时,就可以读取到contentBase中的文件,而devServer中的contentBase指定服务器从哪里提供内容,也就是devServer服务器提供的一个存放打包资源的一个虚拟目录。

在看一个例子,接着上面的配置,设置devServer的public(如果这里不设置publicPath,默认读取output中的publicPath)

webpack配置中的path、publicPath和contentBase

webpack配置中的path、publicPath和contentBase

 webpack配置中的path、publicPath和contentBase

 webpack配置中的path、publicPath和contentBase

所以contentBase通常不需要设置,有些项目中设置成了'./dist' webpack输出目录,其实这里contentBase指定的‘./dist’ 目录是一个内存中的虚拟目录,并不是项目中的实际dist目录。

 

所以简单的理解是output的publicPath会在打包的html文件中引用资源路径添加前缀

devServer中的publicPath表示在浏览器中用此路径可以访问到打包的资源

devServer中的contentBase指定一个虚拟路径来让devServer服务器提供内容

 

这是目前对这几个路径的理解,可能有理解不对的地方

 

参考https://juejin.im/post/5bb085dd6fb9a05cd24da5cf

 

上一篇:vue3.0版本打包后,index.html页面显示空白怎么办


下一篇:CSS3重要内容翻译