目前我正在开发通过Angular CLI生成的角度应用程序,它正在使用webpack。
我们有50多个模型typescript类来保存employee.model.ts,person.model.ts等数据。
在我们的项目中,它目前分散在不同的模块中。我们决定将所有模型放入一个角度模块中,然后所有其他模块应该从一个特定模块导入这些域模型。
我该如何实现这一目标?
我已经阅读了几篇关于打字稿别名功能的帖子,在tsconfig.json文件中我可以添加路径属性。所以这是我到目前为止所尝试的。
ProjectDirectory/src/app
ProjectDirectory/src/app/models
Models文件夹包含employee.model.ts,person.model.ts和50+其他模型。
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 { Employee } from '@my-models'; //<== DOESN'T WORK & THROWS ERROR.
错误
src/app/app.module.ts (20,26): Cannot find module '@my-models'.
是否有任何干净的方法来组织所有模型在一个地方,并有更清晰的导入语句,没有相对路径,如
import {Xyz} from './././././abc.module';
提前感谢大家花时间阅读这个问题。
注意:我阅读了以下文章,但它没有用。
https://decembersoft.com/posts/say-goodbye-to-relative-paths-in-typescript-imports/
https://www.typescriptlang.org/docs/handbook/module-resolution.html
处理此问题的推荐方法是使用barrel。
在models
文件夹中,您可以添加一个index.ts
文件,该文件导出该文件夹中包含的所有类:
export * from './abc.module.ts'; // re-export all of its exports
export * from './xyz.module.ts'; // re-export all of its exports
...
现在需要进口的东西来自桶:
import { Abc, Xyz } from './path-to-models';