vue專案打包上線報錯404解決
技術標籤:前端開發
原因:打包後的dist沒有放到伺服器的根目錄下。
解決方案:vue-cli官方檔案給出的方法如下
預設情況下,Vue CLI 會假設你的應用是被部署在一個域名的根路徑上,例如 https://www.my-app.com/。如果應用被部署在一個子路徑上,你就需要用這個選項指定這個子路徑。例如,如果你的應用被部署在 https://www.my-app.com/my-app/,則設定 publicPath 為 /my-app/。
這個值也可以被設定為空字串 (’’) 或是相對路徑 (’./’),這樣所有的資源都會被連結為相對路徑,這樣打出來的包可以被部署在任意路徑,也可以用在類似 Cordova hybrid 應用的檔案系統中。
首先,檢視build後的dist檔案目錄
可以看出,js、css在index.html的同級目錄下;
然後,檢視index.html,看到下面的程式碼
<script type=text/javascript src=/static/js/app.41ce5f66426864089c57.js></script>
我們先普及下檔案路徑的知識 …/上級目錄 ./同級目錄 /根目錄
看上面的程式碼,js、css檔案的訪問是根目錄,所以我們只需要將根目錄改成同級目錄就可以了。
修改方法:找到config資料夾下的index.js檔案
找到build.assetsPublicPath,將"/“修改成”./"
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: './'
// 下面的省略
}
build.assetsPublicPath【資源的根目錄】
這個是通過http伺服器執行的url路徑。在大多數情況下,這個是根目錄(/)。如果你的後臺框架對靜態資源url字首要求,你僅需要改變這個引數。在內部,這個是被webpack當做output.publicPath來處理的。
後臺有要求的話一般要加上./ 或者根據具體目錄新增,不然引用不到靜態資源
build.productionSourceMap
在構建生產環境版本時是否開啟source map。
dev.port
開發伺服器監聽的特定埠
dev.proxyTable
定義開發伺服器的代理規則。
專案中webpack配置的config/index.js,有dev和production兩種環境的配置 以下介紹的是production環境下的webpack配置的理解
var path = require('path')
2
3 module.exports = {
4 build: { // production 環境
5 env: require('./prod.env'), // 使用 config/prod.env.js 中定義的編譯環境
6 index: path.resolve(__dirname, '../dist/index.html'), // 編譯輸入的 index.html 檔案
7 assetsRoot: path.resolve(__dirname, '../dist'), // 編譯輸出的靜態資源路徑
8 assetsSubDirectory: 'static', // 編譯輸出的二級目錄
9 assetsPublicPath: '/', // 編譯釋出的根目錄,可配置為資源伺服器域名或 CDN 域名
10 productionSourceMap: true, // 是否開啟 cssSourceMap
11 // Gzip off by default as many popular static hosts such as
12 // Surge or Netlify already gzip all static assets for you.
13 // Before setting to `true`, make sure to:
14 // npm install --save-dev compression-webpack-plugin
15 productionGzip: false, // 是否開啟 gzip
16 productionGzipExtensions: ['js', 'css'] // 需要使用 gzip 壓縮的副檔名
17 },
18 dev: { // dev 環境
19 env: require('./dev.env'), // 使用 config/dev.env.js 中定義的編譯環境
20 port: 8080, // 執行測試頁面的埠
21 assetsSubDirectory: 'static', // 編譯輸出的二級目錄
22 assetsPublicPath: '/', // 編譯釋出的根目錄,可配置為資源伺服器域名或 CDN 域名
23 proxyTable: {}, // 需要 proxyTable 代理的介面(可跨域)
24 // CSS Sourcemaps off by default because relative paths are "buggy"
25 // with this option, according to the CSS-Loader README
26 // (https://github.com/webpack/css-loader#sourcemaps)
27 // In our experience, they generally work as expected,
28 // just be aware of this issue when enabling this option.
29 cssSourceMap: false // 是否開啟 cssSourceMap
30 }
31 }