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

13

我在TypeScript中的重新导出有些迷失了方向。假设我创建了一对测试模块:

test1.ts;

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

测试2.ts;

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

我相信我应该能够做到这样;

combined.ts;

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

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

可惜的是,并没有这样的运气。似乎有很多GitHub问题讨论各种方法,包括使用旧的hack export import * from './test1',但它们都似乎争论ES6规范实际上是什么意思,而且没有一个真正起作用。

在这种情况下,应该如何正确地进行打包?我是否走了错误的路来拆分模块?在这里使用命名空间是否更合适?

2个回答

29

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

Rollup,直接导出

您正确的rollup模块将简单地为:

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

然后使用Rollup:

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

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

Rollup,添加命名空间对象

如果您想要使用额外的命名空间导出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();

使用不同的导出名称进行Rollup

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

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

然后使用变成:

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

所以这很有道理,除了一件事 - index.js也是CommonJS吗?如果我在util / index.js中执行我的rollup,使用import * from'../ util'不起作用 - ../ util / index可以。这是ES6的事情吗?如果有影响,我的tsconfig设置为module:commonjs。 - XeroxDucati
隐式加载index.js文件是Node.js特有的功能。最好不要依赖这个功能,特别是因为你可能有一个util.js文件加上一个带有index.js文件的util目录。 - C Snover
1
所以这就是我即将要做的事情 - 在顶层目录中有一个util.js文件,它从'util/<whatever>'导出所有内容,但一旦我有了大量模块,我的顶层目录将变得非常混乱... 有没有更好的方法来拆分util? - XeroxDucati
太棒了,非常感谢您的回答。使用命名空间的卷起正是我正在寻找的。 - Roaders

0

看起来你不能使用 * 导出模块中的所有内容,即使使用 * 作为 localModuleName。

相反,你必须命名其他模块从组合模块中导出的内容。

// combined.ts
export {test1, test3} from './test1'; 
export {test2} from './test2';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接