路由懒加载和代码优化这里就不说了,主要说打包优化
- 使用CDN外部加载资源vue,vuex,vue-router,axios
对于vue, vuex, vue-router,axios等,可以利用webpack的externals参数来配置,这里我们设定只需要在生产环境中才需要使用:
vue.config.js:
// vue.config.js
const isProduction = process.env.NODE_ENV === 'production';
const cdn = {
css: [],
js: [
'https://cdn.bootcss.com/vue/2.5.17/vue.runtime.min.js',
'https://cdn.bootcss.com/vue-router/3.0.1/vue-router.min.js',
'https://cdn.bootcss.com/vuex/3.0.1/vuex.min.js',
'https://cdn.bootcss.com/axios/0.18.0/axios.min.js',
]
}
module.exports = {
chainWebpack: config => {
// 生产环境配置
if (isProduction) {
// 生产环境注入cdn
config.plugin('html')
.tap(args => {
args[0].cdn = cdn;
return args;
});
}
},
configureWebpack: config => {
if (isProduction) {
// 用cdn方式引入
config.externals = {
'vue': 'Vue',
'vuex': 'Vuex',
'vue-router': 'VueRouter',
'axios': 'axios'
}
}
},
}
index.html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<!-- 使用CDN的CSS文件 -->
<% for (var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.css) { %>
<link href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" rel="preload" as="style">
<link href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" rel="stylesheet">
<% } %>
<!-- 使用CDN的JS文件 -->
<% for (var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.js) { %>
<link href="<%= htmlWebpackPlugin.options.cdn.js[i] %>" rel="preload" as="script">
<% } %>
</head>
<body>
<noscript>
<strong>We're sorry but eye-admin doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
<% for (var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.js) { %>
<script src="<%= htmlWebpackPlugin.options.cdn.js[i] %>"></script>
<% } %>
</body>
</html>
打包后的尺寸对比:
用cdn外部加载资源,DOMContentLoaded快了1s多,Load快了2s:
- 使用UglifyJsPlugin插件减少文件体积
vue.config.js:
// 减少体积的插件
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
// 生产环境
const isProduction = process.env.NODE_ENV === 'production';
const cdn = {
css: [],
// cdn加载js文件
js: [
'https://cdn.bootcss.com/vue/2.6.11/vue.runtime.min.js',
'https://cdn.bootcss.com/vue-router/3.1.6/vue-router.min.js',
'https://cdn.bootcss.com/vuex/3.5.1/vuex.min.js',
'https://cdn.bootcss.com/axios/0.20.0/axios.min.js',
]
}
module.exports = {
publicPath:'/',
outputDir:'dist',
assetsDir: "static",
indexPath: "index.html",
lintOnSave: false,//关闭eslint
css: {
// px2rem插件配置,设置原始设计稿的宽度为1920px
loaderOptions: {
postcss: {
plugins: [
require('postcss-px2rem')({remUnit: 192}), // 换算的基数
]
}
}
},
chainWebpack: config => {
// 生产环境配置
if (isProduction) {
// 生产环境注入cdn
config.plugin('html')
.tap(args => {
args[0].cdn = cdn;
return args;
});
}
},
configureWebpack: config => {
if (isProduction) {
// 用cdn方式引入
config.externals = {
'vue': 'Vue',
'vuex': 'Vuex',
'vue-router': 'VueRouter',
'axios': 'axios'
}
config.plugins.push(
// 使用UglifyJsPlugin去掉console 可以略微降低文件大小
new UglifyJsPlugin({
uglifyOptions: {
compress: {
drop_debugger: true,
drop_console: true, //生产环境自动删除console
},
warnings: false,
},
sourceMap: false,
parallel: true //使用多进程并行运行来提高构建速度。默认并发运行数:os.cpus().length - 1。
})
);
}
},
}
- 安装compression-webpack-plugin插件。
前端将文件打包成.gz文件,然后通过nginx的配置,让浏览器直接解析.gz文件,可以大大提升文件加载的速度。
- 开发环境下安装compression-webpack-plugin插件
npm install --save-dev compression-webpack-plugin
- 修改vue.config.js文件配置
vue.config.js:
// 生产环境
const isProduction = process.env.NODE_ENV === 'production';
// 减少体积的插件
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
// 压缩代码插件
const CompressionPlugin = require('compression-webpack-plugin');
// 匹配那些文件会被压缩
const productionGzipExtensions = new RegExp('.(' + ['js', 'css'].join('|') + ')$');
// cdn加载的插件
const cdn = {
css: [],
// cdn加载js文件
js: [
'https://cdn.bootcss.com/vue/2.6.11/vue.runtime.min.js',
'https://cdn.bootcss.com/vue-router/3.1.6/vue-router.min.js',
'https://cdn.bootcss.com/vuex/3.5.1/vuex.min.js',
'https://cdn.bootcss.com/axios/0.20.0/axios.min.js',
]
}
module.exports = {
publicPath:'/',
outputDir:'dist',
assetsDir: "static",
indexPath: "index.html",
lintOnSave: false,//关闭eslint
css: {
// px2rem插件配置,设置原始设计稿的宽度为1920px
loaderOptions: {
postcss: {
plugins: [
require('postcss-px2rem')({remUnit: 192}), // 换算的基数
]
}
}
},
chainWebpack: config => {
// 生产环境配置
if (isProduction) {
// 生产环境注入cdn
config.plugin('html')
.tap(args => {
args[0].cdn = cdn;
return args;
});
//compressionPlugin插件所需要的配置文件
config.plugin('compressionPlugin')
.use(new CompressionPlugin({
filename: "[file].gz[query]",//记得不要用path,用file,不然会打包不成功
algorithm: 'gzip',
test: productionGzipExtensions,
threshold: 10240, //对10K以上的数据进行压缩
minRatio: 0.8,
deleteOriginalAssets: false //是否删除源文件
}));
}
},
configureWebpack: config => {
if (isProduction) {
// 用cdn方式引入
config.externals = {
'vue': 'Vue',
'vuex': 'Vuex',
'vue-router': 'VueRouter',
'axios': 'axios'
}
config.plugins.push(
// 使用UglifyJsPlugin去掉console 可以略微降低文件大小
new UglifyJsPlugin({
uglifyOptions: {
compress: {
drop_debugger: true,
drop_console: true, //生产环境自动删除console
},
warnings: false,
},
sourceMap: false,
parallel: true //使用多进程并行运行来提高构建速度。默认并发运行数:os.cpus().length - 1。
})
);
}
},
}
- 修改nginx配置文件
nginx.conf:
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
#root /zswblog/dist;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
# 配置信息
# 开启动态gzip模式
gzip on;
# 开启静态gzip模式
gzip_static on;
# gizp压缩起点,文件大于1k才进行压缩
gzip_min_length 1k;
# 设置压缩所需要的缓冲区大小,以4k为单位,如果文件为7k则申请2*4k的缓冲区
gzip_buffers 4 32k;
# 设置gzip压缩针对的HTTP协议版本
gzip_http_version 1.1;
# gzip 压缩级别,1-9,数字越大压缩的越好,也越占用CPU时间
gzip_comp_level 5;
# 需要压缩的文件mine类型
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
# 是否在http header中添加Vary: Accept-Encoding,建议开启
gzip_vary on;
# nginx做前端代理时启用该选项,表示无论后端服务器的headers头返回什么信息,都无条件启用压缩
gzip_proxied expired no-cache no-store private auth;
# 不启用压缩的条件,IE6对Gzip不友好,所以不压缩
gzip_disable "MSIE [1-6]\.";
location / {
root /zswblog/dist;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
error_page 404 /404.html;
location = /404.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
保存后使用 nginx -s reload 命令重启nginx服务器,下面是加载该网站时的首屏加载时长