总结了七种方法,
1.路由懒加载
路由配置,component: resolve => require(['@c/home/home'], resolve),
引入路由
var router = new VueRouter({
mode: 'hash',
routes: [
{
path: '/home',
component: resolve => require(['@c/home/home'], resolve),
children: [...common, ...basicSet, ...docManage, ...fileManage, ...cooperateWork]
},
{
path: '/',
redirect: '/auth'
},
{
path: '/auth',
component: resolve => require(['@c/auth/auth'], resolve)
}
]
});
2.cdn引入
public文件夹的index.html用cdn引入,
<script src="https://cdn.staticfile.org/vue/2.6.10/vue.min.js"></script>
<script src="https://cdn.staticfile.org/element-ui/2.13.0/index.js"></script>
<link href="https://cdn.staticfile.org/element-ui/2.13.0/index.css" rel="stylesheet" />
vue.config.js里module.exports中chainWebpack中
config.externals({
'vue': 'Vue',
'element-ui': 'ELEMENT',
});
main.js里面注释element-ui的注册和引入更换
// import ElementUI from 'element-ui';
Vue.use(ELEMENT);//Vue.use(ElementUI)
3.mixin混入
避免重复的代码,把公用的方法写在一个文件里,有用到这个方法的文件引入即可
定义一个 js 文件(mixin.js)
export default {
data() {
return {
name: 'mixin'
}
},
created() {
console.log('mixin...', this.name);
},
mounted() {},
methods: {}
}
在用到的文件中引入这个js
import '@/mixin'; // 引入mixin文件
export default {
mixins: [mixin]
}
4.gzip压缩
cnpm install compression-webpack-plugin --save-dev
在vue.config.js的module.exports中
configureWebpack: {
plugins: [
new CompressionWebpackPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'), //匹配文件名
threshold: 10240, //对10K以上的数据进行压缩
minRatio: 0.8,
deleteOriginalAssets: false //是否删除源文件
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"windows.jQuery": "jquery"
})
]
}
5.去掉.map文件
.map 文件的作用:项目打包后,代码都是经过压缩加密的,如果运行时报错,输出的错误信息无法准确得知是哪里的代码报错。 有了 .map
就可以像未加密的代码一样,准确的输出是哪一行哪一列有错。
在vue.config.js的module.exports 中
productionSourceMap: false, // 生产环境生成sourceMap文件
6.图片压缩
慎用!影响图片质量,易模糊
- 使用https://tinypng.com/压缩图片
或者 - 引入插件
npm install image-webpack-loader --save-dev
在vue.config.js的module.exports 中的chainWebpack中
config.module
.rule('images')
.use('image-webpack-loader')
.loader('image-webpack-loader')
.options({
bypassOnDebug: true
})
.end()
7.去除console.log
- public文件夹的index.html的script中
window.onerror = function () {
return true;
}
var logDebug = false;
console.log = (function (oriLogFunc) {
return function () {
if (logDebug) {
oriLogFunc.apply(this, arguments);
}
}
})(console.log);
- 引入插件
npm install uglifyjs-webpack-plugin --save-dev
在vue.config.js的module.exports 中的chainWebpack中
config
.plugin('uglifyjs-plugin')
.use('uglifyjs-webpack-plugin', [{
uglifyOptions: {
warnings: false,
compress: {
drop_console: true,
drop_debugger: false,
pure_funcs: ['console.log']
}
}
}])
.end()