【问题标题】:How to use tsconfig-paths with ts-node如何将 tsconfig-paths 与 ts-node 一起使用
【发布时间】:2022-11-04 12:58:38
【问题描述】:

如何使用打字稿设置路径以使用 ts-node 运行?然后在编译时将路径编译为绝对路径?

我有以下非常小的结构:

koki.ts:

export const calculate = (a: number, b: number) => {
  return a + b;
};

index.ts:

import { calculate } from "@koki/koki";

const result = calculate(1, 2);
console.log(result);

tsconfig.json:

{
  "ts-node": {
    "transpileOnly": true,
    "require": ["tsconfig-paths/register"]
  },
  "compilerOptions": {
    "target": "es2017",
    "module": "commonjs",
    "lib": ["dom", "es6", "es2017", "esnext.asynciterable"],
    "skipLibCheck": true,
    "sourceMap": true,
    "outDir": "./dist",
    "moduleResolution": "node",
    "removeComments": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "resolveJsonModule": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["*"],
      "@koki/*": ["koki/*"]
    }
  },
  "exclude": ["node_modules"],
  "include": ["./src/**/*.ts"]
}

我正进入(状态:

ts-node src/index.ts 
Error: Cannot find module '@koki/koki'
Require stack:
- /home/pwnage/Documents/github/test-node/src/index.ts

【问题讨论】:

  • 您不能在运行时使用tsconfig.json 中的路径与节点,至少不能单独使用。我们使用typescript-transform-paths 插件来实现,但这也需要使用ttsc 而不仅仅是默认的tsc。但是 Node 在运行时对您的 tsconfig 一无所知,因此您需要在构建期间重写它们的东西。
  • 那是节点,但我也试图用 ts-node 运行,而不是编译它并从 dist 运行。
  • 你需要 tsconfig-paths 来做到这一点:typestrong.org/ts-node/docs/paths

标签: node.js typescript tsconfig-paths


【解决方案1】:

就我而言,

package.json

"scripts": {
    "start": "ts-node -r tsconfig-paths/register src/index.ts",
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-28
    • 2017-09-27
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    相关资源
    最近更新 更多