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) }
新手上路,若有不同想法,可以多多交流,