BundleAnalyzer Webpack externals配置,优化chunk-vendor大小,提高初始加载速度

调整了很多次终于见到效果 , 发现最根本的问题在于 被external的包是否依赖Vue, 如果依赖就要把Vue先加external

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
vue.config.js

const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

module.exports = {
publicPath: '/saas-manager',

// 只用加以下节点 , main.js当中不用调整
configureWebpack: {
externals: {
// 使用elementui 必须要先中vue(因为elementui依赖vue, 而在html文件中这两个资源也必需写在<div id="app"></div> 之前 ),
vue: 'Vue',
'element-ui': 'ELEMENT',
},
},
// 更改编译输出的文件名增加hashcode , 以强制浏览器无法缓存, 保证每次修改能及时看到效果
chainWebpack: (config) => {
config.output.filename('js/[name].[hash:6].js')
.chunkFilename('js/[name].[hash:6].js')
.end();

// 每次yarn serve 新开浏览器显示 BundleAnalyzer(各资源文件大小占比)
config
.plugin('webpack-bundle-analyzer')
.use(BundleAnalyzerPlugin)
.init((Plugin) => new Plugin());

js文件未做任何调整

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
main.js 

import Vue from 'vue';
import ElementUI from 'element-ui';
import axios from 'axios';
import VueAxios from 'vue-axios';
import elementUtils from 'vue-element-utils';

import App from './App.vue';
import router from './router';
import store from './store';

// 以下两个资料在index.html 中引用csn资源, 以减少打包后的文件大小
// import 'element-ui/lib/theme-chalk/index.css';
// import 'bootstrap/dist/css/bootstrap.min.css';

Vue.config.productionTip = false;

Vue.use(ElementUI, {
size: 'small',
zIndex: 3000,
});


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
index.html
<head>
// 外部css
<link href="https://cdn.bootcdn.net/ajax/libs/element-ui/2.14.1/theme-chalk/index.css" rel="stylesheet">
<!-- bootstrap3 会有graph,所以使用bs3 -->
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.css">
</head>
<body>
// 外部js
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.11/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/element-ui/2.14.1/index.js"></script>
...

<div id="app"></div>
</body>