繁体   English   中英

TS 配置路径错误。 错误:找不到模块“@/models/UserSchema”

[英]TS config path error. Error: Cannot find module '@/models/UserSchema'

我正在制作一个 discord 机器人,我正在尝试 typescript 上的路径别名功能。 但是我在使用它时会不断收到此错误。 我正在使用 NodeJs 并使用

这是错误消息

Error: Cannot find module '@/models/UserSchema'
Require stack:
- /mnt/c/Users/ASUS/Documents/_Frastio-Docs/dev/DinderBot/src/index.ts
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._resolveFilename (/mnt/c/Users/ASUS/Documents/_Frastio-Docs/dev/DinderBot/node_modules/module-alias/index.js:49:29)
    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> (/mnt/c/Users/ASUS/Documents/_Frastio-Docs/dev/DinderBot/src/index.ts:13:1)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Module.m._compile (/mnt/c/Users/ASUS/Documents/_Frastio-Docs/dev/DinderBot/node_modules/ts-node/src/index.ts:1056:23)

这是我尝试使用路径时的代码。 它似乎是正确的,在 vscode 上没有错误,但是当我运行应用程序时,它给出了找不到模块错误

import Test from '@/models/TestSchema'
import User from '@/models/UserSchema'

在此处输入图像描述

我的 tsconfig.json

{
  "compilerOptions": {
    "strictNullChecks": true,
    "baseUrl": ".",
    "emitDecoratorMetadata": true,
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "lib": ["es5", "es6"],
    "module": "CommonJS",
    "moduleResolution": "node",
    "outDir": "./dist",
    "paths": {
      "@/*": ["src/*"]
    },
    "resolveJsonModule": true,
    "sourceMap": true,
    "target": "es6",
    "types": ["node"]
  },
  "include": ["**/*.ts"],
  "exclude": ["node_modules"]
}

我的文件夹结构,tsconfig 在 src 文件夹的外面文件夹结构

看起来使用官方repo上解决的ts-node映射paths存在问题。 他们还提供了一个解决方案是使用tsconfig-paths到 map 所以执行以下步骤:

  • 安装tsconfig-paths
npm i -D tsconfig-paths
  • 将以下配置添加到tsconfig.json
{
  "ts-node": {
    "require": ["tsconfig-paths/register"]
  }
}

// Or you can use it in your dev CLI without having to add above config like:
// `"dev": "ts-node -r tsconfig-paths/register path/to/index.ts",`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM