前言:
这里主要介绍output中的publicPath和devServer中的contentBase和publicPath
首先明白两点,
1.在webpack.config.js文件中,output配置只在production环境下起效,devServer只在development环境下有效。
2.devServer运行下所编译的文件皆存在于内存中,不会改变本地文件。在服务运行中如果内存中找不到想要的文件时,devServer 会根据文件的路径尝试去本地磁盘上找,如果这样还找不到才会 404
一. output.publicPath
我们最常接触的output的配置是:
output: {
path: __dirname + "/build",
filename: "[name].bundle.js"
}
那么这里publicPath是用来干嘛的?
其实publicPath被webpack的插件(url-loader,html-webpack-plugin)用于在production环境下更新引用的静态资源的url。
栗子:
output: {
.........
publicPath:'https://a.cdn.com/'
}
那么当你执行打包过后你的静态资源路径就会被加上publicPath的路径
development:
.div{
background:url(./1.png) center top no-repeat;
}
production:
.div{
background:url(https://a.cdn.com/1.png) center top no-repeat;
}
二.devServer.contentBase
引用官网的话就是:
告诉本地服务从哪里提供内容且只有在您想要提供静态文件时才需要这样做
其实就是index.html所在的目录
三.devServer.publicPath
当启动devServer的时候,文件也会被编译,上面说到它只存在于内存中。
publicPath其实就是指定外部访问编译文件的路径
栗子:
devServer配置
devServer: {
publicPath:'/build/',
inline: true
}
index页面
<script src="build/main.bundle.js"></script>
那么当我们的devServer启动的时候做了哪些事儿:
1.首先加载contentPath下面的index.html(由于没有设置),则访问的便是
http://localhost:8080/
2.加载index.html里的静态资源,由于设置了publicPath,那么编译后的文件提供给外部的访问路径就是contentPath + publicPath,也就是
http://localhost:8080/build/
3.由于在内存中找到了该文件则不去读取硬盘中的文件
四.注意项
需要注意的一点是:
当你在项目中用到了html-webpack-plugin的时候,请保证output和devServer的publicPath路径一致
因为html-webpack-plugin在嵌入静态资源的时候使用的是output的publicPath,会导致在devServer运行的时候加载资源报错