ES Modules 与 CommonJS

493 阅读1分钟

ES Modules基本特性

  • 通过给script标签添加type = module的属性,就可以以ES Module的标准执行其中的JS代码
  • ESM 自动采用严格模式,忽略‘use strict’(如使用this)
  • 每个ESM 都是运行在单独的私有作用域中
  • ESM 是通过CORS 的方式请求外部JS模块的
  • ESM的script标签都会延迟执行脚本

ES Modules导入导出方法

// 动态导入模块
// ./module.js
const foo = 'es modules'
export { foo }

// ./app.js
import('./modules.js').then(module=>{
  console.log(module)
})

// ./module.js
const foo = 'es modules'
export { foo }

// ./app.js
import { foo } from './module.js'
console.log(foo)

// ./module.js
export var foo = 'es modules'

// ./app.js
import { foo } from './module.js'
console.log(foo)

// ./module.js
var foo = 'es modules'
export default foo

// ./app.js
import foo from './module.js'
console.log(foo)

// ./module.js
var age = 18;
var name = 'Tom';

function hello () {
	console.log('hello')
}
class Person {}

export { name, age, hello, Person }

// ./app.js
import { name, age, hello, Person } from './module.js'
console.log(foo)

模块集成导入

CommonJS导入导出方法

ES Modules in nodejs

  • 需要将所有.js后缀的文件改为.mjs

      在新版本中,设置package.json中配置type:'module',就不用将扩展名改为.mjs, 如果是在ES module环境中使用commonjs文件,则需要将commonjs后缀改为.cjs
    
  • 启动命令改为 node --experimental-modules 对应文件名.mjs Commonjs模块始终只会导出一个默认成员

不能在CommonJS模块中通过require载入ES Module

如何在ES module中获取文件地址

总结:

  • ESModules中可以导入CommonJS模块
  • CommonJs中不能导入ES Modules模块
  • CommonJS始终只会导出一个默认成员
  • import 不是解构导出对象