简体   繁体   English

Typescript 建立绝对导入节点

[英]Typescript Establishing Absolute Imports Node

I built a project in node using TS, and I'm trying to implement absolute path for imports.我使用 TS 在节点中构建了一个项目,并且正在尝试实现导入的绝对路径。

However, when I run the project it begins failing saying.但是,当我运行该项目时,它开始失败。

[1] Error: Cannot find module 'src/common/logger'
[1] Require stack:
[1] - C:\...xyz\Workspaces\PROJECT\dist\index.js

When I switch 'src/common/logger' to './common/logger' it proceeds to point to other ones that absolute path imports.当我将'src/common/logger'切换到'./common/logger'时,它会继续指向其他绝对路径导入的路径。

I figure its obviously something wrong with my TS config, but I can't seem to see where I am messing up.我认为我的 TS 配置显然有问题,但我似乎看不出我在哪里搞砸了。

Ultimately I want the imports to become 'common/xyz' and 'db/xyz'最终我希望导入成为'common/xyz''db/xyz'

My project directory follows this flow:我的项目目录遵循以下流程:

├───tsconfig.json
├───node_modules
├───dist // output location
└───src
     |───common
     |───db
     └───index.ts
{
  "compilerOptions": {

    /* Language and Environment */
    "target": "es2021",

    /* Modules */
    "module": "commonjs",
    "rootDir": "./src",
    "moduleResolution": "node",
    "baseUrl": ".",
    "paths": {
      "src/*": ["./src/*"],
      "/*": [ "./src/*" ],
    },
    "outDir": "./dist"
  }
}

My thought is that the issue is how I set up the tsconfig.我的想法是问题在于我如何设置 tsconfig。 I tried looking through the documentation, but I clearly am not understanding the paths section.我尝试查看文档,但我显然不理解路径部分。 I've tried several changes to the paths, but still can't seem to get it work.我已经尝试了对路径的一些更改,但似乎仍然无法使其正常工作。

Any help would be greatly appreciated.任何帮助将不胜感激。

Leaving this bread trail for people who come across this issue.为遇到此问题的人留下这条面包之路。

TLDR; TLDR; There is no way with tsconfig only to do it. tsconfig 无法做到这一点。 You would need to use packages such as Webpack, Gulp, or other npm packages to help resolve the absolute imports.您需要使用 Webpack、Gulp 或其他 npm 包等包来帮助解决绝对导入问题。

My advice: If you are working on just getting the project up and running, stick with relative imports for now.我的建议:如果您正在努力让项目启动并运行,那么现在坚持使用相对导入。 Then you can look into the 3rd party tools to implement the absolute pathing.然后您可以查看 3rd 方工具来实现绝对路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM