vue項目打包後資源相對引用路徑的和背景圖片路徑問題

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

 

 

 

 

 新手上路,如有不一樣想法,能夠多多交流,

相關文章
相關標籤/搜索