理解webpack中的publicPath

outPut中的publicPathcss

默認值: 空字符串。html

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

例如:web

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中的爲準。webpack-dev-server

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

  例如:spa

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須要一致。

相關文章
相關標籤/搜索