tsconfig中的绝对路径不起作用

问题描述

我看到了一些关于this problem的问题,但都没有用 我有一个TypeType的nodejs项目。我不喜欢使用相对路径,在tsconfig中设置路径时出现以下错误

找不到模块'@ app / controllers / main'

// main.ts
export const fullName = "xxxx";
...

// app.ts
import { fullName } from '@app/controllers/main'
...

这是我项目的结构:

-node_modules
-src
----controllers
---------------main.ts
----app.ts
-package.json
-tsconfig.json

tsconfig

{
    "compilerOptions": {
        "target": "es5","module": "commonjs","strict": true,"baseUrl": ".","paths": {
            "@app/*": ["src/*"]
        },"esModuleInterop": true,"skipLibCheck": true,"forceConsistentCasingInFileNames": true
    }
}

我的问题在哪里?

谢谢。

解决方法

您的语法正确。

看来,在撰写本文时,ts-node-dev不支持paths的{​​{1}}条目。

github issue讨论了该问题并提供了解决方法。

,

不幸的是(我不知道为什么),Typescript编译器目前不很好地支持路径转换。

这是我的解决方案:

我在this项目中使用了该解决方案。

安装devDependencies

  1. ttypescript -> npm install ttypescript --save-dev -> TTypescript(Transformer TypeScript)通过动态修补编译模块解决了该问题使用tsconfig.json中的转换器。
  2. typescript-transform-paths -> npm install typescript-transform-paths --save-dev ->将绝对导入从tsconfig.json中的路径转换为相对。
  3. tsconfig-paths -> npm install tsconfig-paths --save-dev ->使用此选项加载其位置在“路径”部分中指定的模块tsconfig.json。支持在运行时和通过API加载。
  4. ts-node-dev -> npm install ts-node-dev --save-dev ->当任何所需文件更改时,它都会重新启动目标节点进程(作为标准的节点开发),但在重启之间共享Typescript编译过程

tsconfig.json

使用以下选项更新 tsconfig.json 文件:

{
    "compilerOptions": {
        /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
        "paths": {
            "@app/*": [
                "./src/*"
            ]
        },/* Advanced Options */
        "plugins": [
            {
                "transform": "typescript-transform-paths"
            }
        ],}
}

构建

对于编译阶段,请在配置文件中使用 ttsc 而不是 tsc 。请参见下面的代码段:

npx ttsc --p ./tsconfig.json

具有自动重装功能的开发模式

处于开发人员模式时,请使用以下脚本(将其放入package.json的脚本选项中)以自动使用正确的路径重新加载项目。 src / app.ts 是位于 src 文件夹下的应用程序的“入口点”。

npx ts-node-dev --prefer-ts true --no-notify -r tsconfig-paths/register --watch src --transpileOnly src/app.ts

PS:使用ts-node-dev可以大大提高速度。