文章中英模式
布鲁斯前端JS面试题目 - JavaScript 模块化系统深入解析
深入解析 JavaScript 中的模块化系统,包含 ES Modules 和 CommonJS 的差异、Tree Shaking 机制,以及面试常见问题的完整解答。
文章中英模式
懒得看文章?那就来看视频吧
基本概念
JavaScript 模块化系统主要分为两大类:CommonJS 和 ES Modules (ESM)。这两种模块系统各有特色,用于不同的执行环境:
- •
CommonJS
:Node.js 原生支持,使用 require 和 module.exports - •
ES Modules
:ECMAScript 标准,使用 import 和 export
模块化语法比较
// CommonJS
const math = require('./math');
module.exports = { add };
// ES Modules
import { add } from './math';
export const multiply = (a, b) => a * b;
Tree Shaking 机制
Tree Shaking 是一个现代 JavaScript 应用程序中重要的优化技术,能够移除未使用的代码:
// utils.js
export const used = () => console.log('这个会被保留');
export const unused = () => console.log('这个会被移除');
// main.js
import { used } from './utils';
used(); // 只有 used 函数会被打包,unused 会被移除
🔥 常见面试题目
(一)ES Modules 和 CommonJS 的主要区别?
解答:
// CommonJS - 值的拷贝
let count = 0;
module.exports = { count };
count++; // 不影响已输出的值
// ES Modules - 值的引用
let count = 0;
export { count };
count++; // 会影响输出的值
(二)为什么 Tree Shaking 只支持 ES Modules?
解答:ES Modules 的静态特性使得编译时就能确定依赖关系,而 CommonJS 的动态特性则无法实现:
// CommonJS 动态特性,无法静态分析
if (condition) {
require('./moduleA');
} else {
require('./moduleB');
}
// ES Modules 静态结构
import { moduleA } from './moduleA';
import { moduleB } from './moduleB';
(三)如何优化模块的加载性能?
解答:主要可以通过以下方式优化:
// 1. 动态导入
const MyComponent = () => {
useEffect(() => {
import('./heavyModule')
.then(module => {
// 使用模块
});
}, []);
};
// 2. 路由分割
const Home = lazy(() => import('./pages/Home'));
const About = lazy(() => import('./pages/About'));