面试题答案
一键面试Webpack 配置
- 安装必要插件
- 通常不需要额外安装插件,Webpack 本身支持代码分割功能。但如果使用
html - webpack - plugin
等插件来处理 HTML 与打包后的资源关系,也可安装并配置。 - 例如,安装
html - webpack - plugin
:npm install html - webpack - plugin --save - dev
- 通常不需要额外安装插件,Webpack 本身支持代码分割功能。但如果使用
- 配置
splitChunks
在 Webpack 的optimization
配置项中使用splitChunks
进行代码分割。
module.exports = {
//...其他配置
optimization: {
splitChunks: {
chunks: 'all',
minSize: 30000,
maxSize: 0,
minChunks: 1,
maxAsyncRequests: 5,
maxInitialRequests: 3,
automaticNameDelimiter: '~',
name: true,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
}
}
};
chunks
:指定哪些块进行分割,'all'
表示所有块(initial
、async
和all
可选)。minSize
:分割的块的最小大小(以字节为单位)。minChunks
:表示在分割之前,这个块必须被引用的最小次数。cacheGroups
:定义缓存组,vendors
缓存组用于分割来自node_modules
的代码,default
缓存组用于通用模块的分割。
Vue 组件层面处理方式
- 懒加载普通组件
在 Vue 中,可以使用
defineAsyncComponent
进行组件的懒加载。
import { defineAsyncComponent } from 'vue';
const MyComponent = defineAsyncComponent(() => import('./MyComponent.vue'));
在模板中使用:
<template>
<div>
<MyComponent />
</div>
</template>
- 按需加载路由组件 在 Vue Router 中配置路由时实现按需加载。
import { createRouter, createWebHistory } from 'vue - router';
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/home',
name: 'Home',
component: () => import('./views/Home.vue')
},
{
path: '/about',
name: 'About',
component: () => import('./views/About.vue')
}
]
});
export default router;
这种方式下,只有当用户访问到对应的路由时,才会加载相应的组件,从而提升页面初始加载性能。同时结合 Webpack 的代码分割,将不同路由组件分割成单独的文件,进一步优化加载。