【发布时间】: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