通常我們使用img標簽引入文件,npm run build 打包后 ,因為img為html標簽,打包后他的路徑是由index.html開始訪問的,他走static/img/'圖片名'是能正確訪問到圖片的
而我們寫在css background:url(../xxx/)引入的圖片 ,這時打包后他的路徑是從static/img/’圖片名’是訪問錯誤的,因為在css目錄下並沒有static目錄。所以此時需要先回退兩層到根節點處才可以正確獲取到圖片。
打開build/utils.js publicPath改為 publicPath:'../../',
function generateLoaders (loader, loaderOptions) { const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader] if (loader) { loaders.push({ loader: loader + '-loader', options: Object.assign({}, loaderOptions, { sourceMap: options.sourceMap }) }) } // Extract CSS when that option is specified // (which is the case during production build) if (options.extract) { return ExtractTextPlugin.extract({ use: loaders, publicPath:'../../', fallback: 'vue-style-loader' }) } else { return ['vue-style-loader'].concat(loaders) } }
比如 在app.vue中 請求圖片資源放在assets文件下
background: url('./assets/banner.png') center no-repeat;
打包后,打開瀏覽器無法加載圖片
錯誤的請求路徑 project/dist/static/css/static/img/banner.5db0023.png
正確的路徑project/dist/static/img/banner.5db0023.png