当前位置:网站首页>Use type aliases in typescript

Use type aliases in typescript

2022-07-06 23:57:00 User 6256742

In many packaging tools or use cli The type alias will be provided in the created project , for example Vue-cli Use in @ Can represent absolute path src.

But in use TypeScript Development Node.js There is no such choice in the project , Of course we can be in tsconfig.json Set in path Parameters , But this is only the path without error and is conducive to path prompt , stay ts-node The runtime will still report an error , There is a community called typescript-paths Plug-in to solve the problem , But this plug-in is very unfriendly to incremental compilation (ts After the project is large, you need to compile it in full and change it a little 2 minute ), For this, we can use plug-ins module-alias To solve .

1. First of all, we are still tsconfig.json Set in ts Path alias of , It is possible to ts No error and good path prompt .

 "paths": {
      "@/*": ["src/*"]
    },

Copy

JSON

2. Installing a plug-in module-alias, This is very simple yarn add module-alias perhaps npm intall module-alias

3. Configure the path alias at the top of the entry file ( Can be in package.json But for incremental compilation, you need to copy an additional file )

//  variable aliasing 
import moduleAlias from "module-alias";
moduleAlias.addAlias("@", __dirname);

Copy

TypeScript

The whole configuration can be configured with multiple aliases , At the same time, you can write callback functions . If you use TS Project development can be combined with TS+Node.js Do incremental compilation This article combines project configuration

原网站

版权声明
本文为[User 6256742]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061628470330.html