代码模块化

2 ES6模块

ES6模块基于文件,一个文件就是一个模块。
ES6模块支持异步模块加载。
关键字:importexport

导入和导出

在变量、函数和类等标识符之前使用export

export const message='hello world';

在模块最后一行导出。

const message='hello world';
function sayHello(){
  return message+'!';
}

export {message,sayHello};

在另一文件中导入。

import {message,sayHello} from 'Bear.js'

导入模块中导出的全部的标识符。

import * from 'Bear.js'

默认导出

使用一个标识符代表整个模块的导出。仍然可以导出其他标识符。

export default class Bear{
  constructor(name){
    this.name=name;
  }
}

export function compareBear(bear1,bear2){
  return bear1.name==bear2.name;
}

导入默认导出的内容,不需要花括号,也可以指定任意名称。

import WiredBear from 'Bear.js';
import {compareBear} from 'Bear.js';

可以更简明一些。

import WiredBear,{compareBear} from 'Bear.js';

重命名

重命名export

function niHao(){
  return 'hello';
}

export {niHao as sayHello};
import {sayHello} from 'Greeting.js';

重命名import

function niHao(){
  return 'hello';
}

export niHao;
import {niHao as sayHello} from 'Greeting.js';
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容