You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript+Node.js 18中消除相对导入?

如何消除TypeScript项目中的相对导入?

我当前运行一个基于TypeScript 5.2的后端应用,可编译为Debian服务在生产环境运行(Node 18),也可通过nodemon直接在Docker容器中运行。

项目中存在大量长短不一的相对导入:

import { Shortcut } from './Shortcut';
import { formatQuery } from '../../../../../../helpers/formatQuery';

我希望消除这些相对导入。

我的配置文件

package.json

{
  "name": "toto",
  "version": "1.4.9",
  "description": "tata",
  "scripts": {
    "start:dev": "nodemon --config ./node_modules/@titi/config/nodemon.json",
    "build": "tsc -p tsconfig.json"
  },
  "devDependencies": {
    "jest": "29.6.1",
    "ts-jest": "29.1.0",
    "typescript": "5.2.2"
  },
  "dependencies": {
    "nodemon": "3.0.1",
  },
  "volta": {
    "node": "18.17.0",
    "yarn": "1.22.17"
  }
}

自定义nodemon.json配置

{
  "watch": ["src/", "*.json"],
  "ignore": [
    ".git",
    "public",
    "node_modules/**/node_modules",
    "src/**/*.test.*",
    "src/**/*.spec.*"
  ],
  "ext": "ts,js,json",
  "exec": "tsc -p tsconfig.json --incremental && node --trace-warnings --trace-uncaught build || exit 1"
}

tsconfig.json配置

{
  "compilerOptions": {
    "lib": ["es2020"],
    "module": "commonjs",
    "target": "es2020",
    "moduleResolution": "node",
    "outDir": "../../../build",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "forceConsistentCasingInFileNames": true,
    "allowSyntheticDefaultImports": true,
    "downlevelIteration": true,
    "declaration": true,
    "sourceMap": true,
    "pretty": true,
    "baseUrl": ".",
    "paths": {
      "@services/*": [
        "src/services/*"
      ],
      "@routes/*": [
        "src/routes/*"
      ],
      "@helpers/*": [
        "src/helpers/*"
      ]
    },
  },
  "files": ["../../../src/index.ts"],
}

已尝试的无效方案

  • 设置tsconfig.json的baseUrl属性,无论设为.还是./src,导入import { formatQuery } from 'src/helpers';时均报错:src/services/toto.ts:5:29 - error TS2307: Cannot find module 'src/helpers' or its corresponding type declarations.
  • 添加paths配置,如"@helpers/*": [ "src/helpers/*" ],导入import { formatQuery } from '@helpers';或@helpers/formatQuery时仍报相同错误
  • 在nodemon.json的exec中使用NODE_PATH环境变量,无效
  • 修改VSCode的typescript.preferences.importModuleSpecifier为non-relative,不适用
  • 使用Node.js子路径模式、添加jsconfig.json,均无效

补充说明

src/helpers/index.ts文件存在,内容如下:

export * from './parseString';
export * from './formatQuery';
...

请问我哪里操作有误?是否我的项目架构过于复杂导致无法使用非相对导入?

内容的提问来源于stack exchange,提问作者Paul-Marie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 16:24:54