EcmaScript 6模块规范

Reads: 2002 Edit

  • 导出模块 export (等价于module.exports)
  • 导入模块 import (等价于 require)

新建项目demo2,创建以下目录结构和文件

QQ截图20200223055411

1 导出默认成员

1 语法: 默认成员只能有一个,不然会报错

export default 成员

2 示例 bar.js

export default{
  name : 'mxg'
}

2 导入默认成员

语法:

// 如果模块文件没有 default成员,则加载的是 undefined
import *** from 模块文件

示例: main.js

// ES6 导入
// 默认加载的是 export default 成员
import bar from "./bar"

document.write("a1");
console.log(bar.name)

修改index.html

11060644

运行webpack命令

3 导出非默认成员

语法: 非默认成员必须要有成员名称

export 成员

示例 bar.js

export default {
    name : 'mxg'    
}

// ES6 导出非默认成员
export const x = 'xxx'
export const y = 'yyy'

export function add(a, b){
    return a +b
}

导入非默认成员

语法

//方式一: 按需导入模块成员,采用解构赋值的方式
import {成员名1,成员名2,...,成员名n} from 模块文件

//方式二: 一次导入模块文件的所有成员,包含default成员

示例: main.js

// ES6 导入
// 默认加载的是 export default 成员
//import bar from "./bar"

import * as bar2 from "./bar"
console.log(bar2.x,bar2.y,bar2.add(1,2))

document.write("a1");
console.log(bar2.default.name);

输入命令 webpack ,然后查看结果

关于作者

王硕,网名信平,十多年软件开发经验,业余架构师,精通Java/Python/Go等,喜欢研究技术,著有《PyQt 5 快速开发与实战》《Python 3.* 全栈开发》,多个业余开源项目托管在GitHub上,欢迎微博交流。


Comments

Make a comment

www.ultrapower.com ,王硕的博客,专注于研究互联网产品和技术,提供中文精品教程。 本网站与其它任何公司及/或商标无任何形式关联或合作。