[英]Typescript - simplify imports
Is there way to import modules with alias? 有没有办法导入带有别名的模块? Eg I have angular service in folder
common/services/logger/logger.ts
. 例如,我在文件夹
common/services/logger/logger.ts
有角度服务。 How to make import looks like import {Logger} from "services"
where "services" contains all my services? 如何使导入看起来像
import {Logger} from "services"
其中“服务”包含我的所有服务?
I've looked at this and this but didn't understand how I can use it. 我看着这个和这个 ,但不明白我怎么可以使用它。
Create one file that contains all of your services and give it a name, eg services.ts
. 创建一个包含您所有服务的文件,并为其命名,例如
services.ts
。 That file can be seen as a barrels, because it will contain and export all of your services. 该文件可以看作是桶,因为它将包含并导出您的所有服务。 The file could look like this:
该文件可能如下所示:
export * from './logger/logger';
export * from ...;
etc.
Now you can import this single file as follow: 现在,您可以按以下方式导入该文件:
import * as Services from 'common/services';
Then you can access your servies via Services.Logger
, or directly import the service you want via: 然后,您可以通过
Services.Logger
访问您的Services.Logger
,或通过以下方式直接导入所需的服务:
import {Logger} from 'common/services';
Note, you have change the paths since this is just an example. 注意,您已经更改了路径,因为这只是一个示例。 For more information about this technique, have a look here .
有关此技术的更多信息,请在此处查看 。
To solve this problem I used webpack. 为了解决这个问题,我使用了webpack。 If you want to import dependencies everywhere you want, you will need to add alias in webpack config.
如果要在任何位置导入依赖项,则需要在webpack配置中添加别名。 For example, you have folder
shared
in root with services
folders in it. 例如,您具有在根目录中
shared
文件夹以及其中的services
文件夹。 Folder services
should have index.ts
that exports all services you need (eg Logger
). 文件夹
services
应该具有index.ts
,它可以导出您需要的所有服务(例如Logger
)。 So alias would be "services" => "shared/services"
. 因此别名为
"services" => "shared/services"
。
To make autocomplete work in WebStorm you just need to mark shared
folder as a "Resource root". 要使自动完成功能在WebStorm中起作用,您只需要将
shared
文件夹标记为“资源根”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.