面试题答案
一键面试1. Vue CLI 自定义配置文件
在 Vue CLI 项目中,通常使用 vue.config.js
作为自定义配置文件。首先确保项目已安装 Vue CLI:
npm install -g @vue/cli
然后在项目根目录创建 vue.config.js
文件。
2. Tree - shaking
配置思路: Tree - shaking 是一种通过消除未使用的代码来优化包体积的技术。在 Vue 项目中,它主要依赖 ES6 模块系统。默认情况下,Webpack 会自动进行 Tree - shaking 操作,但我们可以进一步优化配置。
关键代码示例:
在 vue.config.js
中:
module.exports = {
configureWebpack: {
optimization: {
usedExports: true
}
}
};
usedExports: true
标记出未使用的导出,以便在压缩阶段删除它们。
3. 懒加载
配置思路:
- 组件懒加载:对于大型项目中的大量组件,使用懒加载可以将组件的加载推迟到需要时,减少初始加载时间。
- 路由懒加载:在 Vue Router 中,通过懒加载路由组件,可以避免一次性加载所有路由对应的组件。
关键代码示例:
- 组件懒加载:
<template>
<div>
<button @click="loadComponent">Load Component</button>
<component :is="lazyComponent" v-if="lazyComponent"></component>
</div>
</template>
<script>
export default {
data() {
return {
lazyComponent: null
};
},
methods: {
loadComponent() {
this.lazyComponent = () => import('./LazyLoadedComponent.vue');
}
}
};
</script>
- 路由懒加载:在
router/index.js
中:
const routes = [
{
path: '/about',
name: 'About',
component: () => import('@/views/About.vue')
}
];
4. 压缩代码
配置思路: 在构建过程中压缩代码可以显著减小文件体积,提高加载速度。Vue CLI 默认使用 Terser 进行代码压缩。
关键代码示例:
在 vue.config.js
中:
module.exports = {
chainWebpack: config => {
config.optimization.minimizer('terser')
.tap(options => {
const compress = options[0].terserOptions.compress;
// 进一步优化压缩配置,例如删除 console.log
compress.drop_console = true;
return options;
});
}
};
5. 多端适配特定优化需求
Web 端优化:
- 性能监控:可以使用 Google Lighthouse 等工具进行性能监控和优化建议。
- 资源预加载:对于关键资源,如首屏渲染所需的 CSS 和 JavaScript,可以使用
<link rel="preload">
进行预加载。在public/index.html
中:
<link rel="preload" href="<%= BASE_URL %>js/chunk-vendors.js" as="script">
移动端优化:
- 图片优化:使用更适合移动端的图片格式,如 WebP。可以在
vue.config.js
中配置:
const ImageminPlugin = require('imagemin-webpack-plugin').default;
const imageminMozjpeg = require('imagemin-mozjpeg');
module.exports = {
configureWebpack: {
plugins: [
new ImageminPlugin({
test: /\.(jpe?g|png|gif|svg)$/i,
plugins: [
imageminMozjpeg({
quality: 80,
progressive: true
})
]
})
]
}
};
- 响应式布局:使用媒体查询和弹性布局(Flexbox、Grid)来确保页面在不同尺寸的移动设备上正确显示。在 CSS 中:
@media (max - width: 768px) {
body {
font - size: 14px;
}
}
通过以上从 Vue CLI 自定义配置文件入手的综合优化策略,可以有效提升大型 Vue 项目在多端的整体性能。