0%

模块化-1

ES6 模块化

export

ES6 模块化 是 静态编译,在编译阶段就已经引入,而非执行阶段引入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
export const name = 'tang'
const age = 18
const foo = function () {
console.log('function foo');
}
class A {}

const obj = {
type: 'array',
data: []
}

export {
age,
foo as Foo1 ,
A as ClassA,
obj
}
  1. export 导出的是一个接口而非一个具体的值

    1
    2
    3
    export 'string'               // error
    const a = 'a'
    export a // error
  2. export 导出的内容与其对应的值是 动态绑定的,导出的内容发生变化,引入内容值同时变化

  3. export 命令可以出现在模块中的顶层的任何位置,不是文件顶部,而是不能出现在块级作用域内

ES6 模块化 是 静态编译,在编译阶段就已经引入,而非执行阶段引入

1
2
3
if (true) {
export const b = 'b' // error
}
  1. export default 只能导出一次
    导出的是一个 名为 default 的内容

    1
    2
    3
    export default {}
    export default 'string'
    export { foo as default }
  2. 导入再导出

    1
    2
    3
    4
    5
    import { age, name } from './a'
    export { age, name }
    // 相当于
    export { age, name } from './a'
    // 直接导出,在本文件中则不能使用 age, name
  3. 1
    2
    export { name as nameProps } from './a'
    export * from './a'
  4. 1
    2
    3
    4
    export { name as default } from './a
    // 相当于
    import { name } from './a'
    export default name

import

1
2
3
4
5
6
import { name as myName, age, Foo1, obj } from './1'
console.log(name); // 无法访问
console.log(myName); // tang
console.log(age); // 18
Foo1() // function foo
console.log(obj); // {type: "array", data: Array(0)}
  1. 对于全局操作,引入则生效

    1
    2
    // 2.js
    document.title = 'typescript study'
    1
    import './2'
  2. import 命令将提升到模块头部,首先执行
    静态编译,在编译阶段自动提升

  3. 多个重复导入,最终会合并为一个

    1
    2
    3
    4
    import { age } from './1'
    import { name } from './1'
    // 相当于
    import { age, name } from './1'
  4. 1
    2
    import * as temp from './1'
    console.log(temp.ClassA);
  5. 导入 default

    1
    2
    import foo from './1
    import { default as foo } from './1
  6. import() 方法

  • 程序执行阶段动态引入,按需加载
  • 没有正式加入标准
  • webpack 可以实现
  • 返回一个 promise
    1
    2
    3
    4
    const status = 1
    if (status) {
    import('./3')
    }

Nodejs 模块化

Nodejs 模块 遵循 commonjs 模块方案

  1. 内置模块:fs 文件系统模块、net 网络系统模块 。。。
  2. 用户自定义模块

reuqire

1
2
3
4
5
6
7
// 引入的是一个对象,导出的接口作为对象的属性
const info = require('./1')
console.log(info); // { name: 'tang', age: 100 }
console.log(info.age); // 100

const foo = require('./2')
foo() // module.exports

exports

  1. exports

    1
    2
    3
    4
    5
    // 导出的实际上是 exports 这个对象
    // 引入时也是引入对象,访问对象上的属性

    exports.name = 'tang'
    exports.age = 100
  2. module.exports

    1
    2
    3
    4
    5
    // 和 es6 module.exports 相似,导出的是一个接口

    module.exports = function () {
    console.log('module.exports');
    }
-------------本文结束感谢您的阅读-------------