Vue項目build後,圖片加載不出來

vue項目,build之後會對圖片進行處理,具體處理的方式是在文件webpack.base.conf.js中,有如下代碼:

module: {
    rules: [
     {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000, // 1k-----限制文件的大小
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
     }
    ]
}

以上代碼中,使用url-loader對圖片的大小進行限制,在limit之內,webpack會將圖片轉化爲base64,超出limit限制,交給file-loader處理。
如果在limit範圍之內,不會出現圖片加載不出來的情況;
超出limit,webpack會將處理後的圖片放在dist/static/img/中,此時加載圖片將會顯示不出來。具體做法如下:
1、在config/index.js文件內,修改代碼: (列出index.js的部分代碼)

build: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: './', 
}

assetsPublicPath字段值由之前的'/'改爲'./';
2、在webpack.prod.conf.js文件內,output字段,添加代碼(publicPath: './'):

output: {
    publicPath: './', // 添加的代碼
    path: config.build.assetsRoot,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },

3、在utils.js文件裏添加 publicPath:'../../',代碼如下:

// (which is the case during production build)
if (options.extract) {
  return ExtractTextPlugin.extract({
    use: loaders,
    fallback: 'vue-style-loader',
    publicPath: '../../'  // 添加的代碼
  })
} else {
  return ['vue-style-loader'].concat(loaders)
}

以上步驟操作完後,執行命令:npm run build
在build後,dist中的index.html頁面的link、script標籤的引入路徑變爲相對路徑;同時,相關的圖片路徑,也變變爲相對路徑,此時部署項目,不再出現圖片路徑404。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章