問題描述:
300kb的文件加載速度用了5s
1.首先肯定要去掉.map文件
在 config/index.js 文件中將productionSourceMap 的值設置為false. 再次打包就可以看到項目文件中已經沒有map文件
productionSourceMap: false, // https://webpack.js.org/configuration/devtool/#production devtool: '#source-map',
2.vue-router路由懶加載
3.使用gzip壓縮
1),在安裝完依賴插件后,修改config/index.js 文件下 productionGzip:true ;
開啟productionGzip功能必須先install --save-dev compression-webpack-plugin @1.1.12 使用低版本否則會報錯
// 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'],
2),然后在 webback.prod.config.js 中添加如下代碼
3),最后在Nginx 下開啟gzip 。
首先安裝Nginx 服務器,然后將項目文件部署到html文件目錄下,如果端口被占用,可以修改 config/nginx.conf 文件中listen:somename 來修改端口。

開啟gzip:
在config/nginx.config 添加如下配置。
http:{
gzip on;
gzip_static on;
gzip_buffers 4 16k;
gzip_comp_level 5;
gzip_types text/plain application/javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg
image/gif image/png;
}
|
修改完成后,reload一下,重啟服務。
4,使用CDN加載 原文鏈接:
https://blog.
csdn.net/LonewoIf/article/details/87777367
在打包后發現vendor.js 文件占用內存特別大,這里面主要是使用的一些第三方庫,例如 vuex,vue-router,axios,elementUI 等文件
我們除了在使用過程中單個組件引用,還可以使用CDN 加載。
通過在index.html 中直接引入第三方資源來緩解我們服務器的壓力,其原理是將我們的壓力分給了其他服務器站點。
1)引入資源。 在 index.html 中,添加CDN資源,
<!-- 引入Vue.js --> <script src="https://cdn.staticfile.org/vue/2.4.3/vue.min.js"></script> <!-- 引入vuex.js --> <script src="https://cdn.staticfile.org/vuex/3.0.0/vuex.min.js"></script> <!-- 引入vue-router --> <script src="https://cdn.staticfile.org/vue-router/3.0.0/vue-router.min.js"></script> <!-- 引入組件庫 --> <script src="https://cdn.staticfile.org/element-ui/2.4.3/index.js"></script> <!-- 引入樣式 --> <link href="https://cdn.staticfile.org/element-ui/2.4.3/theme-chalk/index.css" rel="stylesheet"> <!-- 引入echarts --> <script src="https://cdn.staticfile.org/echarts/4.1.0/echarts.min.js"></script>
2)添加配置 在 bulid/webpack.base.conf.js 文件中,增加 externals,將引用的外部模塊導入,
第三步:去掉原有的引用
去掉 import:
// import Vue from "vue"; // 引入element 組件 // import ElementUI from "element-ui"; // import "element-ui/lib/theme-chalk/index.css"; // import VueRouter from "vue-router"; // import Vuex from "vuex";
去掉 Vue.use(xxx):
// Vue.use(ElementUI); // Vue.use(VueRouter); // Vue.use(Vuex);
重新 npm run build,會看到此時 vendor.js 體積有所減小了很多。通過開發者模式的Network工具,可以看到 vue.js、vuex.js、vendor.js 等文件會分別由一個線程進行加載。且因為使用了CDN,減輕了帶寬壓力。
注意事項: 1、在第一步引入資源時注意 vue.js 必須在 vue-router、vuex、element-ui 之前引入。 2、在第二步修改配置時注意 “element-ui”: “ELEMENT” 是固定寫法不能更改。 3、如果 element-ui 采用 cdn 引入的方式,vue 不采用 cdn 引入的方式, 這樣打包以后打開 dist 下的 index.html 時頁面空白報錯,必須 vue 和 element-ui 都采用 cdn 引入的方式。