带有Webpack的JS中的TypeScript模块结构

时间:2019-02-08 19:56:04

标签: typescript webpack

我正在尝试使用webpack和具有类似以下文件夹结构的TypeScript库发布:

src/
    module1/
        some-class.ts
        index.ts
    module2/
        some-other-class.ts
        index.ts
    etc/

如果用于TS,我应该能够做到:

import { SomeClass } from 'my-library/module1';

当使用require时,应该能够做到:

const SomeClass = require('my-library/module1');

Webpack需要一个条目(或多个条目)并输出与这些条目匹配的文件。但是,我发现为每个嵌套文件夹定义条目非常不切实际,并且也不知道如何制作像require('my-library/module1/submodule1/etc')这样的深层嵌套条目。

以这种方式创作的,它可能不会遵循ts-loader输出的dts文件。

我在这里想念什么?有没有办法使webpack复制TS源的模块结构?

我使用了错误的工具吗?

如果是这样,人们会用什么来捆绑图书馆?

1 个答案:

答案 0 :(得分:2)

我认为您只需在顶级src /目录中创建index.ts文件,然后从那里导出每个子文件夹,例如export * from 'module1';

创建新模块时,您只需添加新行即可导出正确的目录。

顺便说一句,如果您想从顶层导出实际上是在模块内部更深的内容,则可以使用以下语法export { myFunc } from './module1/nested/myFunc';

在这种情况下,您可以使用require('myLibrary/myFunc')代替require('myLibrary/module1/nested/myFunc')

编辑:如@Dehli所指出,这些索引文件称为Barrels(https://basarat.gitbooks.io/typescript/docs/tips/barrel.html