一、利用路由懒加载
1. 装置插件 npm install --save-dev @babel/plugin-syntax-dynamic-import
2. 批改 babel.config.js 文件
module.exports = {
presets: ['@vue/app'],
"plugins": [
['@babel/plugin-syntax-dynamic-import']
]
}
3.vue.config.js 减少如下配置,勾销 prefetch 和 preload
chainWebpack(config) {config.plugins.delete('preload')
config.plugins.delete('prefetch')
}
二、压缩资源文件(vue 前端打包 chunk-vendors 文件过大的问题)
1. 装置插件(指定版本为 @5.0.1,过高的版本会报错:Cannot read property ‘tapPromise’ of undefined)
npm i compression-webpack-plugin@5.0.1
2. 批改 vue.config.js
const webpack = require('webpack')
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = ['js', 'css']
const isProduction = process.env.VUE_APP_ENV_NAME === 'production'
module.exports = {
configureWebpack: {
plugins: [
new CompressionWebpackPlugin({
algorithm: 'gzip',
test: /\.(js|css|less)$/, // 匹配文件名
threshold: 10240, // 对超过 10k 的数据压缩
minRatio: 0.8,
// deleteOriginalAssets: true // 删除源文件
})
],
},
}
3. 后端配置 nginx
# gzip config
gzip on;
gzip_min_length 1k;
gzip_comp_level 9;
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;
gzip_vary on;
gzip_disable "MSIE [1-6]\.";
server {
listen 80;
# gzip config
gzip on;
gzip_min_length 1k;
gzip_comp_level 9;
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;
gzip_vary on;
gzip_disable "MSIE [1-6]\.";
root /usr/share/nginx/html;
location / {
# 用于配合 browserHistory 应用
try_files $uri $uri/ /index.html;
# 如果有资源,倡议应用 https + http2,配合按需加载能够取得更好的体验
# rewrite ^/(.*)$ https://preview.pro.loacg.com/$1 permanent;
}
location /api {
proxy_pass https://preview.pro.loacg.com;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
}
}
server {
# 如果有资源,倡议应用 https + http2,配合按需加载能够取得更好的体验
listen 443 ssl http2 default_server;
# 证书的公私钥
ssl_certificate /path/to/public.crt;
ssl_certificate_key /path/to/private.key;
location / {
# 用于配合 browserHistory 应用
try_files $uri $uri/ /index.html;
}
location /api {
proxy_pass https://preview.pro.loacg.com;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
}
}