在 TypeScript 中使用绝对导入时,ts-node 'MODULE_NOT_FOUND'

cod*_*ion 22 absolute-path importerror typescript tsconfig

我偶然发现了绝对导入的问题。该存储库可在此处公开:https ://github.com/repetitioestmaterstudiorum/ts-boiler

当我尝试导入具有绝对路径(相对于项目目录)的文件然后执行时npm run dev,否则npm run ts-node src/index.ts出现以下错误:

Error: Cannot find module '/src/constants'
Require stack:
- /Users/<my-username>/<some-path>/ts-boiler/src/index.ts
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue [as _resolveFilename] (/Users/<my-username>/<some-path>/ts-boiler/node_modules/@cspotcode/source-map-support/source-map-support.js:811:30)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/Users/<my-username>/<some-path>/ts-boiler/src/index.ts:1:1)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Module.m._compile (/Users/<my-username>/<some-path>/ts-boiler/node_modules/ts-node/src/index.ts:1597:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Object.require.extensions.<computed> [as .ts] (/Users/<my-username>/<some-path>/ts-boiler/node_modules/ts-node/src/index.ts:1600:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ '/Users/<my-username>/<some-path>/ts-boiler/src/index.ts' ]
}
Run Code Online (Sandbox Code Playgroud)

(出于隐私原因,我的用户名和文件夹结构被混淆)

相对导入(例如import { C } from './constants'在文件内部)src/index.ts工作正常。当将其更改为相应的设置import { C } from '/src/constants'import { C } from 'src/constants'使用相应的tsconfig.json设置时,我收到错误。.js(当我追加或.ts导入时也会发生同样的错误)

tsconfig.json启用前导破折号的绝对导入设置:

"baseUrl": ".",
"paths": {
    /* Support absolute imports with a leading '/' */
    "/*": ["*"]
},
Run Code Online (Sandbox Code Playgroud)

我通常使用 MeteorJS,最近学习了 Remix 教程(以了解该框架)。这两个框架都鼓励绝对导入,我将它们的两个tsconfig.json文件复制到我的项目中(~在 Remix 的设置中添加)来尝试看看它们的配置是否适合我 - 但没有成功!

我还研究了如何启用绝对导入: https: //javascript.plainenglish.io/why-and-how-to-use-absolute-imports-in-react-d5b52f24d53c这导致了同样的错误。

让我更困惑的是,配置了 ESLint 的 VSCode 不会抱怨文件中设置正确的绝对导入tsconfig.json

奇怪的是,有一个导入使用绝对路径,该路径在具有相同设置的项目内运行良好:import type { Constants } from '/types/t.constants'。它也可以在没有“类型”的情况下工作,例如import { Constants } from '/types/t.constants'。可能是因为导入的文件不在“src/”中而是在“types/”中?

也许有人曾经解决过类似的问题?

cod*_*ion 38

经过更多研究,我在这里找到了答案:https://medium.com/@fmoessle/typescript-paths-with-ts-node-ts-node-dev-and-jest-671deacf6428

我的情况需要的是npm i -D tsconfig-paths然后将以下内容添加到我的 tsconfig.json 中:

"ts-node": {
    "require": ["tsconfig-paths/register"]
}
Run Code Online (Sandbox Code Playgroud)

有关此的更多信息:https://github.com/TypeStrong/ts-node#paths-and-baseurl

为了使从src/目录的绝对导入也能在 JEST 测试中工作,我需要将以下内容添加到jest.config.ts

moduleNameMapper: {
    '/src/(.*)': '<rootDir>/src/$1',
},
Run Code Online (Sandbox Code Playgroud)