typescript - 在 TS 1.7 中重新导出 ES6 模块?

标签 typescript ecmascript-6 es6-module-loader typescript1.7

我有点迷失在 TS 再导出中。假设我创建了一对测试模块;

测试1.ts;

export function test1() {
    return 'test';
}

测试2.ts;

export function test2() {
    return 'test';
}

我相信我应该能够做这样的事情;

组合.ts;

export * from './test1';
export * from './test2';

module.exports = {
    test1: test1,
    test2: test2
};

但是,没有这样的运气。似乎有很多 GitHub 问题讨论了各种方法,包括使用 export import * from './test1' 的旧 hack,但他们似乎都在争论 ES6 规范的真正含义,但没有一个实际工作..

像这样进行汇总的正确方法是什么?我只是沿着错误的路径将模块拆分为多个文件吗? namespace 在这里更合适吗?

最佳答案

当你使用 ES 模块时,你不应该使用 module.exportsmodule.exports 是 CommonJS 模块的一部分,而不是 EcmaScript 模块的一部分。

Rollup,直接导出

您正确的汇总模块将是:

export * from './test1';
export * from './test2';

然后使用汇总:

import * as rollup from './combined';
// or `import { test1, test2 } from './combined'`;
// or any other valid import

rollup.test1();
rollup.test2();

汇总,添加命名空间对象

如果你想用额外的命名空间导出 test1 和 test2,那么使用 export {} 语法:

import * as test1 from './test1';
import * as test2 from './test2';
export { test1, test2 };

然后用法变成:

import * as rollup from './combined';
rollup.test1.test1();
rollup.test2.test2();

汇总,使用不同的导出名称

如果您有一些名称冲突,您也可以使用 as 重定向名称,就像使用 import 一样:

export { test1 as t1 } from './test1';
export { test2 as t2 } from './test2';

然后用法变成:

import * as rollup from './combined';
rollup.t1();
rollup.t2();

关于typescript - 在 TS 1.7 中重新导出 ES6 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34557587/

相关文章:

javascript - react | Items.map 不是一个函数

javascript - 关闭Pycharm中的 "Parameter should be initialized"ES6 JavaScript错误

javascript - 使用 ES2015 的复杂名称导入和导出

node.js - Webstorm 意外 token 导出

javascript - 如何在浏览器中集成 System.js 和 babel?

javascript - 使用 TypeORM,向实体添加列时出现 `SQLITE_CONSTRAINT: FOREIGN KEY constraint failed`

javascript - 如何在 typescript 中键入一个动态加载其自己的成员的类

javascript - typescript /ReactJS/setTimeout : 'this' implicitly has type 'any' because it does not have a type annotation. ts

c# - T4 Web API C# 到 Typescript 类库

node.js - 模块没有导出成员 'AWS'