vue项目中若要使用相对路径来得到相应静态资源,css
在通常项目 build 以后都会生成一个 index.htm 文件和 一个 static 文件夹,而 static 这个文件夹须要被放置在根目录下,html
1.须要找到config --- index.js(webpack 是依据index.js 来自动生成文件的)vue
//修改相对路径主要为webpack
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;web
仍是会报错npm
打包后sass
错误的路径服务器
Request URL:
http://192.168.199.230:8020/JinsuiWebsiteForMobile/dist/static/css/static/img/section1-1.e29b671.png
背景正确的路径ui
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这是因为相对路径引发的,url
在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) }
新手上路,如有不一样想法,能够多多交流,