[Javascript] CJS vs ESM
The key differences between CommonJS (CJS) and ECMAScript Modules (ESM) come down to their execution model.
- CommonJS (CJS)
- Synchronous: Each
require()
call blocks execution until the module is loaded. - Cached: Modules are loaded and cached once (so repeated
require()
calls return the same instance).
- Synchronous: Each
- ECMAScript Modules (ESM)
- Asynchronous & Static: The browser and Node.js can analyze dependencies before execution.
- Tree-Shaking Friendly: Unused exports can be removed by bundlers, making code size smaller.
For modren web developmenet, ESM is recommended.
Reason is when we use ESM, we have to declare file dependiences on top of the code
import fn from "./1js"
import wef from "./2js"
It's easier to do some optimiztion (tree shaking...).
CJS: Due to execution is runtime, it is hard to analysis the dependiences.
if (xxx) {
const fn = require("./1js")
} else {
const wef = require("./2js")
}
分类:
Javascript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2024-02-12 [Rust] Intro Enum
2021-02-12 [Bash] Schedule Timed Jobs on macOS with `launchd`
2021-02-12 [Bash] Create a Bash Script that Accepts Named Options with getopts
2021-02-12 [Bash] Use case for Complicated Conditional Statements in Bash
2021-02-12 [Bash] Run `npm install` when package.json changes in githook
2021-02-12 [Bash] Use jq and grep to Find Unused Dependencies in a Project
2020-02-12 [Angular 8 Unit Testing] Angular 8 Unit Testing -- service