1. 程式人生 > >vue專案打包後資源相對引用路徑的和背景圖片路徑問題

vue專案打包後資源相對引用路徑的和背景圖片路徑問題

vue專案中若要使用相對路徑來獲得相應靜態資源,

在一般專案 build 之後都會生成一個 index.htm 檔案和 一個 static 資料夾,而 static 這個資料夾需要被放置在根目錄下,

1.需要找到config --- index.js(webpack 是依據index.js 來自動生成檔案的)

//修改相對路徑主要為

assetsPublicPath: '/',改為 assetsPublicPath: './',
  build: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),
    
//編譯輸入的 index.html 檔案 // Paths assetsRoot: path.resolve(__dirname, '../dist'), // 編譯輸出的靜態資源路徑 assetsSubDirectory: 'static', // 編譯輸出的二級目錄 assetsPublicPath: './', //編譯釋出的根目錄, 編譯之前assetsPublicPath: '/',之前沒有.;由於是引入相對路徑,所以改為"./".可配置為資源伺服器域名或 CDN 域名 productionSourceMap: true, //map檔案為可以準確顯示哪裡報錯,是否開啟 cssSourceMap,當然打包的時候可以設定為false,檔案小些,但是如果有錯誤,控制檯不會報具體位置
// https://webpack.js.org/configuration/devtool/#production devtool: '#source-map', // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin
productionGzip: false, // 是否開啟 gzip productionGzipExtensions: ['js', 'css'], // 需要使用 gzip 壓縮的副檔名 // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report }

2.以上只是解決了引入圖片的路徑,但在css檔案中使用background屬性  background: url(../../../../static/img/company/profile/section1-1.png) 10rem;

還是會報錯

 打包後

錯誤的路徑

Request URL: http://192.168.199.230:8020/JinsuiWebsiteForMobile/dist/static/css/static/img/section1-1.e29b671.png

背景正確的路徑

Request URL: http://192.168.199.230:8020/JinsuiWebsiteForMobile/dist/static/img/section1-1.e29b671.png   Webpack將所有靜態資源都認為是模組,而通過loader,幾乎可以處理所有的靜態資源,圖片、css、sass之類的。並且通過一些外掛如extract-text-webpack-plugin,可以將共用的css抽離出來

 區別就是多了static/css這是由於相對路徑引起的,

在build => util.js 裡找到ExtractTextPlugin.extract增加一行:publicPath: '../../',主要解決背景圖片路徑的問題。

判斷是否有這個資源,否則重新定義publicPath這個路徑

 

 

  if (options.extract) {
      return ExtractTextPlugin.extract({
        use: loaders,
        fallback: 'vue-style-loader',
        publicPath: '../../'
      })
    } else {
      return ['vue-style-loader'].concat(loaders)
    }

 

 

 

 

 新手上路,若有不同想法,可以多多交流,