zjx304

通常我们使用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

 

分类:

技术点:

相关文章: