webpack之公共路徑
阿新 • • 發佈:2019-01-28
公共路徑(Public Path)用在生產環境下,想將靜態檔案統一使用cdn載入的情況下。
import webpack from 'webpack';
// 如果預先定義過環境變數,就將其賦值給`ASSET_PATH`變數,否則賦值為根目錄
const ASSET_PATH = process.env.ASSET_PATH || '/';
export default {
output: {
publicPath: ASSET_PATH
},
plugins: [
//該外掛幫助我們安心地使用環境變數
new webpack.DefinePlugin({
'process.env.ASSET_PATH' : JSON.stringify(ASSET_PATH)
})
]
};
相關例子
webpack-dev-server環境下,path、publicPath、區別與聯絡
path:指定編譯目錄而已(/build/js/),不能用於html中的js引用。
publicPath:虛擬目錄,自動指向path編譯目錄(/assets/ => /build/js/)。html中引用js檔案時,必須引用此虛擬路徑(但實際上引用的是記憶體中的檔案,既不是/build/js/也不是/assets/)