[英]How to use absolute path with Typescript?
I have a project that written in Typescript on NodeJS.我有一个在 NodeJS 上用 Typescript 编写的项目。 I am using relative path for my modules to import another.
我正在使用我的模块的相对路径来导入另一个。 But this usage is getting dirty while project is growing.
但是随着项目的增长,这种用法变得越来越脏。 Because of that I want to convert relative paths to absolute path.
因此,我想将相对路径转换为绝对路径。
Here is my project folder structure:这是我的项目文件夹结构:
src
├── controllers
├── repositories
├── services
│ ├── user.service.ts
|── tsconfig.json
I want to use import another module like below.我想使用导入另一个模块,如下所示。
import userServices from "src/services/user.service";
tsconfig.json配置文件
"moduleResolution": "node",
"baseUrl": ".",
"paths": {
"*": ["src/*"]
}
Above configurations is not working on my workspace.以上配置不适用于我的工作区。
Could you help me about that?你能帮我解决这个问题吗?
Add this in your tsconfig.将此添加到您的 tsconfig.xml 文件中。 Change the path as required by you
根据您的需要更改路径
{
"compilerOptions": {
"baseUrl": "./src"
}
}
There is a TypeScript feature that allows this.有一个TypeScript功能允许这样做。
You can modify your src/tsconfig.json
file to enable this, under compilerOptions
, add the following:您可以修改
src/tsconfig.json
文件以启用此功能,在compilerOptions
下,添加以下内容:
{
"compilerOptions": {
// ...
"paths": {
"*": [
"./*",
"app/*",
"../node_modules/*"
]
}
}
You can obviously change the pattern key and values as needed.您显然可以根据需要更改模式键和值。 You add or remove folders, you can change the order, etc.
您添加或删除文件夹,您可以更改顺序等。
You can also choose a prefix instead of just *
(especially if it cases problems), you can use something like ~/*, and your imports will then be all from '~/shared/sample'
etc.您还可以选择前缀而不仅仅是
*
(尤其是在出现问题的情况下),您可以使用类似 ~/* 的内容,然后您的导入将全部来自'~/shared/sample'
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.