假设您只想要您所询问的最终结果,而不是专门try 使用TypeScrip的module
语法,那么您可以简化一点,然后有几个选项.
简单地说,您不需要Foo.ts
和Bar.ts
中的export module mylib { /* ... */ }
个包装器,只需要:
export class Foo
// ...
}
和
export class Bar
// ...
}
然后,问题就变成了你希望如何从index.ts
个国家进口这些产品.
模块命名空间对象
What you have now in index.ts
is actually just fine for one way it could be used: It creates two named exports, Foo
和 Bar
. If you want to write code using those via a mylib
object, you can create that on import:
import * as mylib from "../src";
// ^^^^^^^^^^
That import
syntax says "Import the module namespace object for the module 和 assign it to a binding called mylib
." If the module namespace object doesn't already exist for that module, it'll be created.
进口后的用法如问题mylib.Foo
等所示.
But doing it that way, it's also possible to use import { Foo } from "../src";
和/or import { Bar } from "../src";
. Normally that's a good thing, but if you don't want to allow that, you won't want to do individual named exports.
Note that import * as mylib
will defeat tree-shaking, if that's important to what you're doing. (Which is part of why import { Foo }
和 such are normally a good thing.) But it's the person using your library who makes that decision; your library doesn't prevent tree-shaking by itself.
导出对象
如果您不想采用上面的模块命名空间对象方法,可以从index.ts
中导出一个对象:
export const mylib = { Foo, Bar };
...或可能将其冻结导出,以便无法添加、删除或重新分配属性:
export const mylib = Object.freeze({ Foo, Bar });
那么导入就像您在问题中所展示的那样:
import { mylib } from "../src";
使用量为mylib.Foo
等.
Beware that this defeats tree-shaking, 和 not just based on how users use it, but at the library level (by not having Foo
和 Bar
exports people could use instead). I wouldn't recommend it.
两者都有
Finally, you could support both named individual exports 和 a single named object export. In that case, the exports in index.ts
would look like this:
export { Foo, Bar };
export const mylib = Object.freeze({Foo, Bar});
如果您这样做了,您就让使用代码的人来决定是使用import { Foo }
还是import { mylib }
.这保持了库对树摇动的友好性,同时还为整个库提供了命名导出(如果有用的话).