If most directories of a project contain no more than 2-3 TypeScript files and all of their exports should be accessible when importing the containing directory somewhere else, this results in a lot of index.ts
files with predictable content.
Directory: my-component
my-component-config.ts
my-component.ts
index.ts
What does index.ts
contain? Of course, it contains
export * from "./my-component-config"
export * from "./my-component"
Which is obvious.
For 10 component directories, that means: 10 index.ts
files containing 100% redundant information.
How can I make TypeScript(/Node) implicitly create index.ts
files on the fly, that need not be stored on the hard disk?
To import all modules from a directory in TypeScript, we can create a module that reexports all modules that were imported. export { default as A } from "./a"; export { default as B } from "./b"; to import the default exports from modules a and b .
index. ts help us to keep all related thing together and we don't need to worry about the source file name. We can import all thing by using source folder name.
The allowJs setting allows JavaScript files to be imported inside your TypeScript files. The setting basically allows JavaScript and TypeScript files to live in the same project.
Component isn't a well defined concept in TypeScript & node.js, but module and package are.
In general, module is a source file, let's ignore the exceptions. So by creating index.ts
files per directory, you are generating façade modules aggregating only a few file/modules each. If all you are looking to do is organize your source files into logical components, you don't need the per-directory façade, you can simply import each file individually rather than a directory at a time.
At a higher level, if you have a package that consists of a number of different directories, it can have a single index.ts
façade at package-level. That file would exported each file/module just once, no need for index.ts
per directory. So this might look like (assuming each is a .ts file):
export * from './IntStream';
export * from './misc/Interval';
export * from './misc/IntervalSet';
export * from './Lexer';
...
I don't think there's a way to import a directory in TS without and index file
check these questions if you haven't
How to import all modules from a directory in TypeScript?
Typescript 1.8 modules: import all files from folder
I think the best approach is to write a script to generate index.ts
that imports all files in the directory, and run that script every time you add/remove a file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With