fe-notes icon indicating copy to clipboard operation
fe-notes copied to clipboard

ESM 和 CJS 模块规范区别

Open Inchill opened this issue 3 years ago • 0 comments

  • 两者的模块导入导出语法不同,CommonJs 是通过 module.exports,exports 导出,require 导入;ESModule 则是 export 导出,import 导入。
  • CommonJs 是运行时加载模块,ESModule 是在静态编译期间就确定模块的依赖。
  • ESModule 在编译期间会将所有 import 提升到顶部,CommonJs 不会提升 require。
  • CommonJs 导出的是一个值拷贝,会对加载结果进行缓存,一旦内部再修改这个值,则不会同步到外部。ESModule 是导出的一个引用,内部修改可以同步到外部。
  • CommonJs 中顶层的 this 指向这个模块本身,而 ESModule 中顶层 this 指向 undefined。
  • CommonJS 加载的是整个模块,将所有的接口全部加载进来,ESModule 可以单独加载其中的某个接口。

Inchill avatar Aug 12 '22 09:08 Inchill