簡體   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