1. 程式人生 > >理解webpack中的publicPath

理解webpack中的publicPath

取值 index info .com 問題 都沒有 server ... head

outPut中的publicPath

默認值: 空字符串。

  publicPath是非常有必要配置的,他是項目中引入靜態資源(js、css)時的基礎路徑。

例如:

outPut.publicPath = ‘/dist/‘;

  在使用html-webpack-plugin插件打包後的html文件(下圖)可以看到,引入js文件的路徑為“publicPath+靜態資源“。敲黑板劃重點,這裏publicPath應該寫“以根目錄的方式表示的路徑,如:/dist/”或者是絕對路徑,不應該是相對路徑。因為將靜態資源放在CDN上時,使用相對路徑是無法訪問到資源的。如果不設置pablicPath行不行,答案是不行。不設置的話默認取值為空字符串(pablicPath: ‘ ‘),那麽使用html-webpack-plugin打包後的html中引入的js路徑為 src="../folder1.a095318635a306de0d2e.js",對,成了相對路徑了。所以如果在生產環境上,publicPath設置成絕對路徑最好。

技術分享圖片

webpack-dev-server中的publicPath

默認值:‘/’。註意,如果你output和devServer中都沒有配置publicPath,那麽devServer的publicPath默認值為‘/’;但是如果output中配了publicPath,devServer中沒配,那麽devServer中publicPath的默認值以output中的為準。

  在開發階段,我們要用devServer啟動一個開發服務器,這裏也有一個publicPath需要配置。webpack-dev-server打包的文件是放在內存中的而不是本地上,這些打包後的資源對外的根目錄就是publicPath。

  例如:

devServer: {
  ...
  publicPath: ‘/dist/‘    
}

  那麽我們可以在瀏覽器中輸入,http://localhost:9000/dist/ + 資源名,就可以訪問到該資源(下圖)。註意:devServer中的publicPath需要跟outPut中的一致,或則不設置publicPath,他會默認與output中的一致。

技術分享圖片

斜杠/的含義

  配置中/代表url根路徑,例如http://localhost:9000/dist/js/test.js中的http://localhost:9000/

常見問題:

 瀏覽器打開http://localhost:9000/index.html時頁面空白。這是因為output與devServer中的publicPath不一致,導致資源沒有引入進頁面裏。

例子:

假如你的配置如下就會出現頁面空白的問題

output: {
  ...
  publicPath: ‘/dist/‘        
}

devServer: {
  ...
  publicPath: ‘/assets/‘    
}

  html-webpack-plugin插件在打包html(下圖)時,裏面引入js文件的路徑會是src="/dist/資源名" 。但是http://localhost:9000/dist/folder1.0bad1ca562f90da47034.js是引入不到該資源的,而http://localhost:9000/assets/folder1.0bad1ca562f90da47034.js可以引入到該資源。體會下這句話,"開發環境時,用webpack-dev-server打包的資源是存放在devServer.publicPath路徑下",你就會明白了。所以output和devServer中的publicPath需要一致。技術分享圖片

理解webpack中的publicPath