TS转口让我迷路了。假设我创建了一对测试模块;
test1.ts;
export function test1() {
return 'test';
}
test2.ts;
export function test2() {
return 'test';
}
我相信我应该能够做这样的事情;
组合;
export * from './test1';
export * from './test2';
module.exports = {
test1: test1,
test2: test2
};
但是,没有这种运气。似乎有很多GitHub问题在讨论各种解决方法,包括一个古老的hack使用方法,export import * from './test1'
但它们似乎都在争论ES6规范的真正含义,而实际上却没有。
做这样的汇总的正确方法是什么?我是否只是沿着错误的路径将模块拆分成多个文件?命名空间在这里更合适吗?
使用module.exports
ES模块时不应该使用;module.exports
是CommonJS模块的一部分,而不是EcmaScript模块的一部分。
您正确的汇总模块将只是:
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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句