Let's say I have this directory structure:
src
├──Utils
| ├──File2.ts
| ├──File3.ts
index.ts
tsconfig.json
I know you can set path aliases inside tsconfig.json like so:
{
"compilerOptions": {
.....
"paths": {
"Utils/*": ["src/Utils/*"],
}
}
}
And then I can use these aliases inside my index.ts:
import { File2 } from 'Utils/File2';
import { File3 } from 'Utils/File3';
I am sure you noticed the redundancy: even so if the File2
and File3
are in the same folder we have to write the import
for each file inside Utils
folder.
Is it possible to groups these files under one import and use it like in the example below?
import { File2, File3 } from 'Utils';
I tried this configuration but it doesn't work:
{
"compilerOptions": {
"paths": {
"Utils": ["src/Utils/*"],
}
}
}
EDIT
Also, I would like NOT to use a barrel file like index.ts
where I export everything from the Utils
folder.
That is solvable by using a barrel file. Create an index.ts
file in /Utils
and add
export * from './File2';
export * from './File2';
and in your tsconfig
{
"compilerOptions": {
"paths": {
"Utils": ["src/Utils"]
}
}
}
It is not possible group these imports without using a barrel file. However, there are libraries that can generate these files for you if you don't want the hassle of manually maintaining them like barrelsby. Alternatively, you could write your own script to keep them up to date.