代码分割(Code Splitting)和 Tree Shaking 是现代前端工程优化打包体积、提升应用性能的核心技术。
代码分割
将代码拆分为多个“块”(chunks),实现按需加载,减少初始加载时间。
- 动态导入
// 动态导入(运行时按需加载)
const loadModule = async () => {
const { heavyFunction } = await import('./heavyModule.js');
return heavyFunction(data);
};
// React 中常用的懒加载
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));
- 基于路由的分割
// React Router v6
const router = createBrowserRouter([
{
path: '/',
element: <Layout />,
children: [
{ index: true, element: <Home /> },
{
path: 'dashboard',
// 懒加载组件
lazy: () => import('./pages/Dashboard'),
},
],
},
]);
- Webpack 配置分割策略
// webpack.config.js
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
commons: {
name: 'commons',
minChunks: 2, // 被2个及以上入口引用
minSize: 0,
},
},
},
},
};
Tree Shaking(摇树优化)
静态分析代码,移除未被使用的导出。
- 使用 ES Module 语法
// 支持 Tree Shaking
export const utilA = () => {}; // 如果未使用,会被移除
export const utilB = () => {};
// 不支持 Tree Shaking(避免)
module.exports = { utilA, utilB };
- 标记副作用(package.json)
{
"sideEffects": [
"*.css", // CSS文件有副作用
"*.scss",
"./polyfill.js"
],
"sideEffects": false // 若无副作用
}
- 生产模式启用
// webpack.config.js
module.exports = {
mode: 'production', // 自动启用TerserPlugin进行Tree Shaking
optimization: {
usedExports: true, // 标记已使用导出
minimize: true, // 压缩时移除未使用代码
},
};
最佳实践
Next
// 自动代码分割 + 动态导入
import dynamic from 'next/dynamic';
const HeavyComponent = dynamic(
() => import('../components/HeavyComponent'),
{
loading: () => <p>Loading...</p>,
ssr: false // 禁用服务端渲染
}
);
React
// 入口文件
import { lazy, Suspense } from 'react';
const AdminPanel = lazy(() =>
import(/* webpackChunkName: "admin" */ './AdminPanel')
);
function App() {
return (
<Suspense fallback={<Loading />}>
<AdminPanel />
</Suspense>
);
}
Vue
// 组合式API + defineAsyncComponent
import { defineAsyncComponent } from 'vue';
const AsyncComp = defineAsyncComponent(() =>
import('./components/MyComponent.vue')
);
评论区