我不明白为什么
ts-node
在启用 esm 时无法解析别名
我做了一个小项目试图尽可能地隔离问题
package.json
{
"type": "module"
}
tsconfig.json
{
"compilerOptions": {
"module": "es2020",
"baseUrl": "./",
"paths": {
"$lib/*": [
"src/lib/*"
]
},
},
"ts-node": {
"esm": true
}
}
test.ts
import { testFn } from "$lib/module"
testFn()
lib/module.ts
export function testFn () {
console.log("Test function")
}
命令
ts-node -r tsconfig-paths/register src/test.ts
解决方案来自:https://github.com/TypeStrong/ts-node/discussions/1450#discussion-3563207
目前,ESM 加载器不处理 TypeScript 路径映射。要使其正常工作,您可以使用以下自定义加载程序:
// loader.js
import {
resolve as resolveTs,
getFormat,
transformSource,
load,
} from "ts-node/esm";
import * as tsConfigPaths from "tsconfig-paths"
export { getFormat, transformSource, load };
const { absoluteBaseUrl, paths } = tsConfigPaths.loadConfig()
const matchPath = tsConfigPaths.createMatchPath(absoluteBaseUrl, paths)
export function resolve(specifier, context, defaultResolver) {
const mappedSpecifier = matchPath(specifier)
if (mappedSpecifier) {
specifier = `${mappedSpecifier}.js`
}
return resolveTs(specifier, context, defaultResolver);
}
然后使用加载器:
node --loader loader.js index.ts
警告:这仅适用于没有扩展名的模块说明符。例如, import
/foo/bar
有效,但 import /foo/bar.js
和 import /foo/bar.ts
则无效。
记住还要安装这些软件包:
"ts-node": "^10.9.1",
"tsconfig-paths": "^4.1.2",
我建议使用esno
esno src/test.ts
您可以使用 @bleed- believer/path-alias 执行您的 ESM 项目(需要在项目中安装 ts-node):
npm i --save @bleed-believer/path-alias
使用 ts-node 执行源文件:
node --no-warnings --loader @bleed-believer/path-alias/esm ./src/test.ts
假设
"outDir": "./dist"
,直接使用节点执行转译代码(绕过 ts-node):
node --no-warnings --loader @bleed-believer/path-alias/esm ./dist/test.js
如果您不想使用该库来执行转译后的项目,您可以使用 swc (此转译器解析路径别名),或者您可以在使用 tsc 转译您的项目后使用 tsc-alias。