問題
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.mian.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然後本地解壓 執行。