Error: Cannot find module XXX (typescript aliases)

Error: Cannot find module XXX (typescript aliases)

这听起来像是一个常见错误。但就我而言,我找不到原因。我正在为另一个项目创建一个 NPM 包作为后端 API。我正在使用打字稿和节点。

我想将我的导入语句从 import XX from "../../../XXX" 更改为 import XX from "@XX",我使用 PHP storm 作为代码编辑器,它说我的代码很好。

但是当我 运行 带有 npx npx ts-node src/index 的脚本时,它会 returns 这个:

Error: Cannot find module '@authentication/SignUp'
Require stack:
- /Users/Youssef_1/Projects/driver-seat-amplify-api/src/index.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue [as _resolveFilename] (/Users/Youssef_1/Projects/driver-seat-amplify-api/node_modules/@cspotcode/source-map-support/source-map-support.js:679:30)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:999:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/Users/Youssef_1/Projects/driver-seat-amplify-api/src/index.js:6:18)
    at Module._compile (node:internal/modules/cjs/loader:1099:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ '/Users/Youssef_1/Projects/driver-seat-amplify-api/src/index.js' ]
}

我的映射:

index.ts:

import {SignUp, ConfirmSignUp, ResendSignUp} from "@authentication/SignUp";
import SignIn from "./Authentication/SignIn";
import Validator from "./Services/Validator";
import {RegexPatterns, RegexTypes} from "./Enums/Regex";
import SignOut from "./Authentication/SignOut";
import DeleteAccount from "./Authentication/DeleteAccount";
import UserManagement from "./Authentication/UserManagement";
import "./app.config";

export default {
    SignIn,
    SignUp,
    SignOut,
    ConfirmSignUp,
    ResendSignUp,
    Validator,
    UserManagement,
    RegexPatterns,
    RegexTypes,
    DeleteUser: DeleteAccount,
}

tsconfig.json:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "moduleResolution": "node",
    "forceConsistentCasingInFileNames": true,
    "alwaysStrict": true,
    "baseUrl": "./src/",
    "sourceMap": true,
    "paths": {
      "@authentication/*": ["Authentication/*"]
    }
  }
}

babel.config.js

module.exports = {
    plugins: [
        "@babel/plugin-transform-typescript",
        "@babel/preset-env",
        ["module-resolver", {
            "root": ["./src"],
            "alias": {
                "authentication": "./src/Authentication",
            }
        }]
    ],
    presets: [
        "@babel/plugin-transform-typescript",
        "@babel/preset-env"
    ],
};

有什么想法吗?

这拯救了我的一天:(已接受的答案)。

安装 ts-node 为我解决了这个问题。