Reputation: 65
Currently I am working on angular app that is generate through Angular CLI & it is using webpack.
We have 50+ model typescript classes to hold data such as employee.model.ts , person.model.ts etc.
In our project currently it is scattered all over the place in different modules. We decided to put all the models into one angular module & then all other modules should be importing these domain models from one particular module.
How do I achieve this ?
I have read couple of posts regarding typescript alias feature where in tsconfig.json file I could add path property. So here is what I have tried so far.
ProjectDirectory/src/app
ProjectDirectory/src/app/models
Models folder contains employee.model.ts , person.model.ts & 50+ other models.
tsconfig.js
{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"typeRoots": ["node_modules/@types"],
"lib": ["es2017", "dom"],
"baseUrl": "src",
"paths": {
"@my-models/*": ["models/*"]
}
}
}
Import statement I tried on other component.
import { Employee } from '@my-models'; //<== DOESN'T WORK & THROWS ERROR.
Error
src/app/app.module.ts (20,26): Cannot find module '@my-models'.
Is there any clean way to organize all models in one place & have cleaner import statements that does not have relative paths such as
import {Xyz} from './././././abc.module';
Thanks everyone in advance to take time to read the question.
Note : I read following articles but it did not work.
https://decembersoft.com/posts/say-goodbye-to-relative-paths-in-typescript-imports/
https://www.typescriptlang.org/docs/handbook/module-resolution.html
Upvotes: 1
Views: 1061
Reputation: 8171
The recommended approach to handling this is by using a barrel.
In your models
folder you can add an index.ts
file which exports all the classes contained in that folder:
export * from './abc.module.ts'; // re-export all of its exports
export * from './xyz.module.ts'; // re-export all of its exports
...
now what needs to be imported comes from the barrel:
import { Abc, Xyz } from './path-to-models';
Upvotes: 2