如何在 Typescript ESM 项目中使用“@/”别名?

问题描述 投票:0回答:1

我正在尝试使用 ESM 运行我的脚本:

ts-node --esm -r tsconfig-paths/register -T src/server/api/jobs/index.ts

但是,它似乎无法像

import '@/server/init.ts
那样处理我的导入:

CustomError: Cannot find package '@/server' imported from /Users/me/Sites/myapp/src/server/api/jobs/index.ts

我尝试将其添加到我的

tsconfig.json

    "paths": {
      "@/*": ["src/*"]
    },

我还尝试更改我的“package.json”的“名称”:

"name": "@/server",

我的文件夹结构是:

/myapp
  package.json
  tsconfig.json
  /src
    /server
      /api
        /jobs
          index.ts

这是我的

tsconfig.json

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "allowImportingTsExtensions": true,
    "allowJs": true,
    "baseUrl": "./src",
    "checkJs": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "incremental": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "lib": ["dom", "dom.iterable", "ES5"],
    "module": "ESNext",
    "moduleResolution": "NodeNext",
    "noEmit": true,
    "noUncheckedIndexedAccess": true,
    "pretty": true,
    "resolveJsonModule": true,
    "rootDir": ".",
    "skipLibCheck": true,
    "strict": true,
    "target": "ESNext",
    "types": ["node"],
    "paths": {
      "@/*": ["src/*"]
    },
    "plugins": [
      {
        "name": "next"
      }
    ]
  },
  "include": [
    ".eslintrc.cjs",
    "next-env.d.ts",
    "**/*.ts",
    "*.js",
    "**/*.js",
    "**/*.tsx",
    "**/*.cjs",
    "**/*.mjs",
    ".next/types/**/*.ts",
    "./src/*",
    "src/*"
  ],
  "exclude": ["node_modules"]
  // "ts-node": {
  //   "esm": true,
  //   "experimentalSpecifierResolution": "node",
  //   "require": ["tsconfig-paths/register"]
  // }
}
node.js typescript es6-modules
1个回答
0
投票

路径别名在运行时不起作用,您必须自己处理这个问题。选项是使用 npm 包,如

tsc-alias
tsconfig-paths
– 不幸的是,后者不适用于 ESM(请参阅 this

© www.soinside.com 2019 - 2024. All rights reserved.