博客·
加载优化
按需引入
1. elementUI
下载
# npm
npm install babel-plugin-component -D
# yarn
yarn add babel-plugin-component
配置
build: {
splitChunks: {
chunks: 'all',
name(module) {
if (module.resource && /^.*\/node_modules\/(element-ui)\/.*$/.test(module.resource){
return 'element-ui'; // 指定要分割的模块名称为 "element-ui"
} else {
return false; // 不需要分割的模块返回 false
}
},
},
transpile: [/^element-ui/],
babel: {
plugins: [
[
'component',
{
libraryName: 'element-ui',
styleLibraryName: 'theme-chalk'
}
]
]
}
}
2.lodash(对比)
import _ from 'lodash'
直接引入
import throttle from 'lodash/throttle'
单个功能引入(使用)
压缩代码
1. 开启gzip压缩
下载
# npm
npm install nuxt-precompress -D
# yarn
yarn add nuxt-precompress
nuxt.config.js配置
export default {
// ...
modules: ['nuxt-precompress'],
nuxtPrecompress: {
enabled: true,
report: false,
test: /.(js|css|html|txt|xml|svg)$/,
middleware: {
enabled: true,
enabledStatic: true,
encodingsPriority: ['br', 'gzip'],
},
gzip: {
enabled: true,
filename: '[path].gz[query]',
threshold: 10240,
minRatio: 0.8,
compressionOptions: { level: 9 },
},
brotli: {
enabled: true,
filename: '[path].br[query]',
compressionOptions: { level: 11 },
threshold: 10240,
minRatio: 0.8,
},
}
// ...
}
服务器nginx配置
// 开启gzip及其他配置
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
2. 代码压缩
build: {
// 开启代码压缩
compress: true,
// 优化器配置
optimizer: {
// 启用 CSS 压缩
css: {
minimize: true
},
// 启用 JavaScript 压缩
js: {
compress: {
drop_console: true, // 移除 console 语句
collapse_vars: true, // 内嵌定义了但是只用到一次的变量
reduce_vars: true // 提取出出现多次但是没有定义成变量去引用的静态值
}
}
},
// Webpack 配置
webpack(config, { isDev, isClient }) {
if (!isDev && isClient) {
// 生产环境客户端构建配置
config.optimization.minimize(true);
}
}
}
3. 代码分割
build: {
// 启用代码分割,将第三方库和公共代码分割到单独的文件中
splitChunks: {
chunks: 'all',
name(module) {
if (module.resource && /^.*\/node_modules\/(element-ui)\/.*$/.test(module.resource){
return 'element-ui'; // 指定要分割的模块名称为 "element-ui"
} else {
return false; // 不需要分割的模块返回 false
}
},
layouts: true,
pages: true,
commons: true,
}
}
asyncData
有利于SEO,服务器加载
async asyncData({ app, params }) {
try {
const { articleId } = params
const res = await app.$API.article.detail(articleId)
return { article: res.data }
} catch (error) {
return { article: {} }
}
}
CDN
阿里云OSS存储静态资源
渲染优化
- 节流 处理滚动加载
- 防抖 处理搜索
- 骨架屏