【问题标题】:How to use paths with ts-node?如何在 ts-node 中使用路径?
【发布时间】:2022-01-10 02:49:58
【问题描述】:

我有这个项目结构:

如何配置tsconfig.json 以使用paths,例如@app/@server/

我试试这个:

{
    "compilerOptions": {
        "module": "CommonJS",
        "target": "es5",
        "lib": [
            "esnext",
            "dom"
        ],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "noFallthroughCasesInSwitch": true,
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": false,
        "baseUrl": "..",
        "paths": {
            "@app/*": [
                "app/*"
            ],
            "@server/*": [
                "server/*"
            ]
        }
    },
    "include": [
        "."
    ]
}

相同的配置适用于webpackts-loader,但是当我运行npx ts-node server/index.ts 时出现错误:

npx ts-node server/index.ts 
Error: Cannot find module '@server/a'

server/index.ts :

import a from '@server/a'

console.log('This is index.ts')

a()

【问题讨论】:

标签: node.js typescript ts-node


【解决方案1】:

您的配置适用于 webpack,因为您从项目根目录运行 webpack。它不适用于server.ts,因为路径是相对于其目录的。试试:

"paths": {
  "@app/*": [
    "../app/*"
  ],
  "@server/*": [
    "../server/*"
  ]
}

如果您需要为两者都这样做,则需要两个不同的 tsconfig.json - 一个在根目录中,一个在 appserver 中。

看看我的项目:https://github.com/mmomtchev/rlayers

它经常使用这个功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 2018-10-09
    相关资源
    最近更新 更多