前言:
這里主要介紹output中的publicPath和devServer中的contentBase和publicPath
首先明白兩點(diǎn)尝抖,
1.在webpack.config.js文件中,output配置只在production環(huán)境下起效顽爹,devServer只在development環(huán)境下有效通砍。
2.devServer運(yùn)行下所編譯的文件皆存在于內(nèi)存中厕宗,不會(huì)改變本地文件觉增。在服務(wù)運(yùn)行中如果內(nèi)存中找不到想要的文件時(shí)彻亲,devServer 會(huì)根據(jù)文件的路徑嘗試去本地磁盤上找孕锄,如果這樣還找不到才會(huì) 404
一. output.publicPath
我們最常接觸的output的配置是:
output: {
path: __dirname + "/build",
filename: "[name].bundle.js"
}
那么這里publicPath是用來(lái)干嘛的?
其實(shí)publicPath被webpack的插件(url-loader睹栖,html-webpack-plugin)用于在production環(huán)境下更新引用的靜態(tài)資源的url硫惕。
栗子:
output: {
.........
publicPath:'https://a.cdn.com/'
}
那么當(dāng)你執(zhí)行打包過(guò)后你的靜態(tài)資源路徑就會(huì)被加上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
引用官網(wǎng)的話就是:
告訴本地服務(wù)從哪里提供內(nèi)容且只有在您想要提供靜態(tài)文件時(shí)才需要這樣做
其實(shí)就是index.html所在的目錄
三.devServer.publicPath
當(dāng)啟動(dòng)devServer的時(shí)候,文件也會(huì)被編譯野来,上面說(shuō)到它只存在于內(nèi)存中。
publicPath其實(shí)就是指定外部訪問(wèn)編譯文件的路徑
栗子:
devServer配置
devServer: {
publicPath:'/build/',
inline: true
}
index頁(yè)面
<script src="build/main.bundle.js"></script>
那么當(dāng)我們的devServer啟動(dòng)的時(shí)候做了哪些事兒:
1.首先加載contentPath下面的index.html(由于沒(méi)有設(shè)置)踪旷,則訪問(wèn)的便是
http://localhost:8080/
2.加載index.html里的靜態(tài)資源曼氛,由于設(shè)置了publicPath,那么編譯后的文件提供給外部的訪問(wèn)路徑就是contentPath + publicPath令野,也就是
http://localhost:8080/build/
3.由于在內(nèi)存中找到了該文件則不去讀取硬盤中的文件
四.注意項(xiàng)
需要注意的一點(diǎn)是:
當(dāng)你在項(xiàng)目中用到了html-webpack-plugin的時(shí)候舀患,請(qǐng)保證output和devServer的publicPath路徑一致
因?yàn)閔tml-webpack-plugin在嵌入靜態(tài)資源的時(shí)候使用的是output的publicPath,會(huì)導(dǎo)致在devServer運(yùn)行的時(shí)候加載資源報(bào)錯(cuò)