前端学习-ES Modules

166 阅读2分钟

ES Modules 特性

  • 自动采用严格模式,忽略 'use strict'
  • 每个 ESM 模块都是单独的私有作用域
  • ESM 是通过 CORS 去请求外部 JS 模块的
  • ESM 的 script 标签会延迟执行脚本,等同于defer
 <!-- 通过给 script 添加 type = module 的属性,就可以以 ES Module 的标准执行其中的 JS 代码了 -->
<script type="module">
    console.log('this is es module')
</script>

导入和导出

导出模块

//单独导出成员
export var name = 'foo module'

export function hello () {
   console.log('hello')
}

export class Person {}


//一起导出
var name = 'foo module'

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

class Person {}

export { name, hello, Person }



//导出时进行重命名
export {
   hello as fooHello
}


//作为默认值导出
export default name

导入模块

  • 导入的成员是引用类型
  • 导入的成员是只读的,无法被修改
  • 导入的模块必须是完整路径,后缀名不可省略
  • 导入的模块支持相对路径,绝对路径,完整的URL
import { name, hello, Person } from './module.js'
console.log(name, hello, Person)

//导入成员重命名
import { name as newName,  } from './module.js'

//接收默认导入成员
import name from './module.js'

//只导入模块不导入成员
import {} from './module.js'
import './module.js'

//导入所有的成员
import * as mod from './module.js'

//动态加载模块
import('./module.js').then(function (module) {
   console.log(module)
})

//同时导入默认成员和其他成员
import { name, age, default as title } from './module.js'
import title, { name, age } from './module.js'


//导出导入的模块
export { Avatar } from './avatar.js'

ES Modules in Browser

Polyfill 兼容方案
在不支持ES Modules的浏览器上运行相关代码

<script nomodule src="https://unpkg.com/promise-polyfill@8.1.3/dist/polyfill.min.js"></script>
<script nomodule src="https://unpkg.com/browser-es-module-loader@0.4.1/dist/babel-browser-build.js"></script>
<script nomodule src="https://unpkg.com/browser-es-module-loader@0.4.1/dist/browser-es-module-loader.js"></script>
<script type="module">
    import { foo } from './module.js'
    console.log(foo)
</script>

ES Modules in Node.js

与 CommonJS 模块交互

  • ES Module 中可以导入 CommonJS 模块
  • CommonJS 中不能导入 ES Module 模块
  • CommonJS 始终只会导出一个默认成员
  • 注意 import 不是解构导出对象
// es-module.mjs

export const foo = 'es module export value'

// ES Module 中可以导入 CommonJS 模块
import mod from './commonjs.js'
console.log(mod)

// 不能直接提取成员,注意 import 不是解构导出对象
import { foo } from './commonjs.js'
console.log(foo)


// commonjs.js

// CommonJS 模块始终只会导出一个默认成员
module.exports = {
   foo: 'commonjs exports value'
}
exports.foo = 'commonjs exports value'

// 不能在 CommonJS 模块中通过 require 载入 ES Module
const mod = require('./es-module.mjs')
console.log(mod)