创建vue-config.js文件
设置不同模式的打包入口
把main.js文件删除,创建main-prod.js和main-dev.js
module.exports = {
chainWebpack: config => {
// 判断当前的编译模式,设置入口的打包文件
config.when(process.env.NODE_ENV === 'production', config => {
config.entry('app').clear().add('./src/main-prod.js')
})
config.when(process.env.NODE_ENV === 'development', config => {
config.entry('app').clear().add('./src/main-dev.js')
})
}
}
合并优化
默认情况下,通过import语法导入的第三方依赖包,会被打包到同一个文件中
造成文件体积过大
1
声明后,打包时发现该包名,就不会合并到同一个文件下,而是在去window全局查找直接使用
config.set('externals', {
vue: 'Vue',
'vue-router': 'VueRouter',
axios: 'axios',
lodash: '_',
echarts: 'echarts',
nprogress: 'NProgress',
'vue-quill-editor': 'VueQuillEditor'
})
2
将main-prod
中的样式表删除,
在public/index.js
文件中添加外部资源引用
<!-- 富文本编辑器 的样式表文件 -->
<link rel="stylesheet" href="https://cdn.staticfile.org/quill/1.3.4/quill.core.min.css" />
<link rel="stylesheet" href="https://cdn.staticfile.org/quill/1.3.4/quill.snow.min.css" />
<link rel="stylesheet" href="https://cdn.staticfile.org/quill/1.3.4/quill.bubble.min.css" />
<script src="https://cdn.staticfile.org/vue/2.5.22/vue.min.js"></script>
<script src="https://cdn.staticfile.org/vue-router/3.0.1/vue-router.min.js"></script>
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
<script src="https://cdn.staticfile.org/lodash.js/4.17.11/lodash.min.js"></script>
<script src="https://cdn.staticfile.org/echarts/4.1.0/echarts.min.js"></script>
<script src="https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.js"></script>
<!-- 富文本编辑器的 js 文件 -->
<script src="https://cdn.staticfile.org/quill/1.3.4/quill.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-quill-editor@3.0.4/dist/vue-quill-editor.js"></script>
优化element-ui
配置完,文件小了很多,但还是很大,于是对element-ui
优化
在main-prod.js
中,注释element-ui按需加载的代码
在index.html
的头部区域,通过CND加载element-ui的js和样式
<!-- element-ui 的样式表文件 -->
<link rel="stylesheet" href="https://cdn.staticfile.org/element-ui/2.8.2/theme-chalk/index.css" />
<!-- element-ui 的 js 文件 -->
<script src="https://cdn.staticfile.org/element-ui/2.8.2/index.js"></script>
为不同模式下添加标题
在main-prod.js
中为html添加属性isProd
开发模式为false,发布模式为true,
并在public/index.js中进行判断
config.plugin('html').tap(args => {
args[0].isProd = false
return args
})
<title><%= htmlWebpackPlugin.options.isProd ? '' : 'dev - ' %>电商后台管理系统</title>
路由懒加载
当打包构建项目时,javaScript包会变得非常大,影响页面加载,把不同路由对应的组件分割成不同的代码块,然后路由被访问的时候才加载对应组件,这样效率更高
具体见链接
- 安装
@babel/pugin-syntax-dynamic-import
包
- 在
babel.config.js
配置文件中声明该插件
- 将路由改为按需加载的形式,示例代码如下
const Foo = () => import(/* webpackChunkName: "group-foo"*/ './Foo.vue')
const Bar= () => import(/* webpackChunkName: "group-foo"*/ './Bar.vue')
const Baz= () => import(/* webpackChunkName: "group-boo"*/ './Baz.vue')