ES6 模块化
export
ES6 模块化 是 静态编译,在编译阶段就已经引入,而非执行阶段引入
1 | export const name = 'tang' |
export
导出的是一个接口而非一个具体的值1
2
3export 'string' // error
const a = 'a'
export a // errorexport
导出的内容与其对应的值是 动态绑定的,导出的内容发生变化,引入内容值同时变化export
命令可以出现在模块中的顶层的任何位置,不是文件顶部,而是不能出现在块级作用域内
ES6 模块化 是 静态编译,在编译阶段就已经引入,而非执行阶段引入
1 | if (true) { |
export default
只能导出一次
导出的是一个 名为 default 的内容1
2
3export default {}
export default 'string'
export { foo as default }导入再导出
1
2
3
4
5import { age, name } from './a'
export { age, name }
// 相当于
export { age, name } from './a'
// 直接导出,在本文件中则不能使用 age, name1
2export { name as nameProps } from './a'
export * from './a'1
2
3
4export { name as default } from './a
// 相当于
import { name } from './a'
export default name
import
1 | import { name as myName, age, Foo1, obj } from './1' |
对于全局操作,引入则生效
1
2// 2.js
document.title = 'typescript study'1
import './2'
import 命令将提升到模块头部,首先执行
静态编译,在编译阶段自动提升多个重复导入,最终会合并为一个
1
2
3
4import { age } from './1'
import { name } from './1'
// 相当于
import { age, name } from './1'1
2import * as temp from './1'
console.log(temp.ClassA);导入 default
1
2import foo from './1
import { default as foo } from './1import() 方法
- 程序执行阶段动态引入,按需加载
- 没有正式加入标准
- webpack 可以实现
- 返回一个 promise
1
2
3
4const status = 1
if (status) {
import('./3')
}
Nodejs 模块化
Nodejs
模块 遵循 commonjs
模块方案
- 内置模块:fs 文件系统模块、net 网络系统模块 。。。
- 用户自定义模块
reuqire
1 | // 引入的是一个对象,导出的接口作为对象的属性 |
exports
exports
1
2
3
4
5// 导出的实际上是 exports 这个对象
// 引入时也是引入对象,访问对象上的属性
exports.name = 'tang'
exports.age = 100module.exports
1
2
3
4
5// 和 es6 module.exports 相似,导出的是一个接口
module.exports = function () {
console.log('module.exports');
}