如何在多个文件中使用ES6模块系统?

时间:2018-07-26 10:04:23

标签: javascript module

我想一次在多个文件中使用 ES6模块系统。 示例:我有一个入口点index.js 文件,所有代码都将在其中运行 而且我还有2个其他文件,例如 exampleOne.js和example.Two.js 。因此我想将其他两个文件中的代码执行到名为 index.js 的入口点文件中。那我该怎么做 我已经尝试过但没有成功

1 个答案:

答案 0 :(得分:0)

您将要从exampleOne.jsexampleTwo.js文件中导出模块,然后将它们导入index.js中。看起来像这样:

exampleOne.js

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

exampleTwo.js

export function subtract(a, b) {
    return a - b;
}

index.js

import {add} from './exampleOne';
import {subtract} from './exampleTwo';

console.log(add(2,3)); // 5
console.log(subtract(2,1)); // 1