BRUCE_FEBRUCE_FE

EN/CH Mode

BRUCE_FE JS Interview Notes - JavaScript Module Systems In-depth Analysis

In-depth analysis of JavaScript modular systems, including differences between ES Modules and CommonJS, Tree Shaking mechanisms, and complete answers to common interview questions.

影片縮圖

Lazy to read articles? Then watch videos!

Basic Concepts

JavaScript module systems are mainly divided into two categories: CommonJS and ES Modules (ESM). These two module systems each have their own characteristics and are used in different execution environments:

  • CommonJS: Natively supported by Node.js, uses require and module.exports
  • ES Modules: ECMAScript standard, uses import and export

Module Syntax Comparison

// CommonJS
const math = require('./math');
module.exports = { add };

// ES Modules
import { add } from './math';
export const multiply = (a, b) => a * b;

Tree Shaking Mechanism

Tree Shaking is an important optimization technique in modern JavaScript applications that can remove unused code:

// utils.js
export const used = () => console.log('This will be kept');
export const unused = () => console.log('This will be removed');

// main.js
import { used } from './utils';
used(); // Only the used function will be bundled, unused will be removed

🔥 Common Interview Questions

(1) What are the main differences between ES Modules and CommonJS?

Answer:

// CommonJS - Copy of values
let count = 0;
module.exports = { count };
count++; // Doesn't affect the exported value

// ES Modules - Reference to values
let count = 0;
export { count };
count++; // Will affect the exported value

(2) Why does Tree Shaking only support ES Modules?

Answer: The static nature of ES Modules allows dependency relationships to be determined at compile time, while the dynamic nature of CommonJS cannot achieve this:

// CommonJS dynamic nature, cannot be statically analyzed
if (condition) {
  require('./moduleA');
} else {
  require('./moduleB');
}

// ES Modules static structure
import { moduleA } from './moduleA';
import { moduleB } from './moduleB';

(3) How to optimize module loading performance?

Answer: Optimization can be achieved mainly through the following methods:

// 1. Dynamic imports
const MyComponent = () => {
  useEffect(() => {
    import('./heavyModule')
      .then(module => {
        // Use the module
      });
  }, []);
};

// 2. Route splitting
const Home = lazy(() => import('./pages/Home'));
const About = lazy(() => import('./pages/About'));