ES6 模块化 关键字export和import

ES6 模块化 关键字export和import

@ixenos 2021年11月10日10点17分

 

 

1.ES6中一个模块就是一个包含JS代码文件,一般来说,模块中所有变量对其他模块不可见,除非我们进行导出。模块系统使用export和import进行模块的导出引入。

 

2.导出方式

(1) name export

① 两种方式

1) 对于要导出的变量加上export  (export const a、export function b)

=====================================

export const sqrt = Math.sqrt;

export function square(x) {

    return x * x;

}

=====================================

2) 用列表统一导出 (export {a,b})

=====================================

const sqrt = Math.sqrt;

function square(x) {

    return x * x;

}

export {sqrt, square}

=====================================

(2) default export

① 一个模块只能有一个认导出

② 导入的名称可以和导出的名称不一致

=====================================

//------ myFunc.js ------

//`没有名字`

export default function() {...};

 

//------ main.js ------

//`随便命名`

//`注意这里认导出在导入时不需要用{}。`

import myFunc from 'myFunc';

myFunc();

=====================================

 

3.重命名export和import

(1) 目的:解决导出命名冲突

(2) 导入重命名

=====================================

// 这两个模块都会导出以`flip`命名的东西。

// 要同时导入两者,我们至少要将其中一个名称改掉。

import {flip as flipOmelet} from "eggs.js";

import {flip as flipHouse} from "real-estate.js";

=====================================

认导入的重命名

=====================================

import { default as foo } from 'lib';

import foo from 'lib';

=====================================

 

 

(3) 导出重命名

=====================================

function v1() { ... }

function v2() { ... }

 

export {

  v1 as streamV1,

  v2 as streamV2,

  v2 as streamLatestVersion

};

=====================================

 

认导出的重命名

=====================================

//------ module1.js ------

export default 123;

 

//------ module2.js ------

const D = 123;

export { D as default };

=====================================

 

 

拓展: ES6模块化与CommonJS模块化

相关文章

原文连接:https://www.cnblogs.com/dupd/p/5951311.htmlES6...
以为Es6,javascript第一次支持了module。ES6的模块化分为导...
视频讲解关于异步处理,ES5的回调使我们陷入地狱,ES6的Prom...
TypeScript什么是TypeScript?TypeScript是由微软开发的一款开...
export class AppComponent { title = 'Tour of heroes...
用 async/await 来处理异步昨天看了一篇vue的教程,作者用as...