面试题答案
一键面试1. 代码分割
- 原理:将代码按路由、按需加载等规则拆分成多个较小的文件,避免初始加载时一次性加载过大的代码块,从而提升页面加载速度。
- 在 Vue CLI 中的应用:
- 路由懒加载:在 Vue Router 配置中,使用
import()
语法实现路由组件的懒加载。例如:
- 路由懒加载:在 Vue Router 配置中,使用
const router = new VueRouter({
routes: [
{
path: '/about',
name: 'About',
component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
}
]
})
这样,只有在访问 /about
路由时,才会加载 About.vue
对应的代码块。
- 异步组件:对于非路由组件,也可以使用
import()
实现异步加载。在组件定义时:
import Vue from 'vue';
const AsyncComponent = () => import('./components/AsyncComponent.vue');
Vue.component('AsyncComponent', AsyncComponent);
当该组件需要渲染时才会加载其代码。
2. Tree - shaking
- 原理:Tree - shaking 是一种通过消除未使用的代码来减小打包体积的优化技术。它依赖 ES6 模块的静态结构,即编译时就能确定模块的导入和导出,从而剔除未使用的模块。
- 在 Vue CLI 中的应用:Vue CLI 默认支持 Tree - shaking。只要项目使用 ES6 模块语法(
.mjs
或在package.json
中设置"type": "module"
并使用.js
后缀),Webpack 会自动进行 Tree - shaking。例如,如果有一个工具函数模块:
// utils.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
在另一个模块中只使用 add
函数:
import { add } from './utils.js';
console.log(add(1, 2));
打包时,subtract
函数的代码不会被包含进最终的 bundle 中,从而减小了打包体积。
3. 其他构建优化策略
- 开启 gzip 压缩:
- 原理:在服务器端对响应数据进行 gzip 压缩,浏览器接收后再解压,可显著减少数据传输量,提升加载速度。
- 在 Vue CLI 中的应用:可以使用
compression-webpack-plugin
插件。安装后在vue.config.js
中配置:
const CompressionPlugin = require('compression-webpack-plugin');
module.exports = {
configureWebpack: {
plugins: [
new CompressionPlugin({
test: /\.js$|\.html$|\.css$/,
threshold: 10240
})
]
}
};
- 优化图片资源:
- 原理:对图片进行压缩、转换为合适的格式(如 WebP)等操作,减小图片体积,加快图片加载。
- 在 Vue CLI 中的应用:可以使用
image-webpack-loader
插件。安装后在vue.config.js
中配置chainWebpack
:
module.exports = {
chainWebpack: config => {
config.module
.rule('images')
.use('image-webpack-loader')
.loader('image-webpack-loader')
.options({
mozjpeg: {
progressive: true,
quality: 65
},
// optipng.enabled: false will disable optipng
optipng: {
enabled: false
},
pngquant: {
quality: [0.65, 0.90],
speed: 4
},
gifsicle: {
interlaced: false
},
// the webp option will enable WEBP
webp: {
quality: 75
}
})
.end();
}
};
4. 提升项目性能的方式
- 提升加载速度:代码分割使得初始加载的代码量减少,用户能更快看到页面内容。例如,路由懒加载避免了所有路由组件在首页加载时就全部加载,加快了首屏渲染速度。
- 减小打包体积:Tree - shaking 剔除未使用代码,gzip 压缩减少传输数据量,优化图片资源降低图片占用空间,这些都直接减小了项目整体的体积,无论是在加载还是运行时,都能提升性能,减少用户等待时间。