文章中英模式
布魯斯前端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'));