解決vue-cli npm run build之後vendor.js檔案過大的問題(打包優化)
阿新 • • 發佈:2018-12-31
問題
vue-cli npm run build
命令預設把dependencies中的依賴統一打包,導致vendor.js檔案過大,出現首屏載入過於緩慢的問題。
解決方案
像vue、axios、element-ui這些基本上不會改變的依賴我們可以把它們用cdn匯入,沒有必要打包到vendor.js中。
1.在專案根目錄index.html使用cdn節點匯入
<div id="app"></div> <!-- 先引入 Vue --> <!--開發環境--> <script src="https://cdn.bootcss.com/vue/2.5.3/vue.js"></script> <!--生產環境--> <!--<script src="https://cdn.bootcss.com/vue/2.5.3/vue.min.js"></script>--> <!-- 引入元件庫 --> <script src="https://cdn.bootcss.com/axios/0.17.1/axios.min.js"></script> <script src="https://cdn.bootcss.com/element-ui/1.4.10/index.js"></script>
2.專案根目錄下build/webpack.base.config.js
中新增externals
externals: {
vue: 'Vue',
'element': 'element-ui',
'axios':'axios',
},
3.main.js
中import ... from ...
就可以去掉了,若沒去掉webpack還是會把對應的依賴進行打包。
2018.01.27補充
在專案config/index.js
中可以開啟gzip壓縮,對打包優化也有很大的幫助
1.首先安裝外掛 compression-webpack-plugin
cnpm install --save-dev compression-webpack-plugin
2.設定productionGzip: true
// 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: true, productionGzipExtensions: ['js', 'css'], // 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
3.npm run build
執行後會發現每個js和css檔案會壓縮一個gz字尾的資料夾,瀏覽器如果支援g-zip 會自動查詢有沒有gz檔案 找到了就載入gz然後本地解壓 執行。