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)
    }

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

原文地址:https://www.cnblogs.com/jiayeyuan/p/10135987.html