簡體   English   中英

Typescript 找不到模塊 無法解決

[英]Typescript Module not found Can't resolve

我正在構建一個 react + typescript 應用程序,在該應用程序中,我創建了一個模塊,該模塊具有在我的項目類中使用的所有接口。 我的 IDE 可以很好地解析這些接口,但 webpack 總是發送以下錯誤。 我嘗試了不同的方法,但無法將其帶到 go 之外。

任何幫助將不勝感激

ERROR in ./assets/src/Pages/Login.tsx Module not found: Error: Can't resolve 'seeyouftp' in 'var/www/app/assets/src/Pages'
 @ ./assets/src/Pages/Login.tsx 43:18-38
 @ ./assets/src/Config/App.tsx
 @ ./assets/entries/bundle.js

我的定義文件在這里

|— definitions
     |— types.d.ts
|— entries
|— fonts
|— less
|— src

我的定義文件的摘錄

declare module 'seeyouftp' {
  interface User {
    admin: boolean;
    roles: string[];
    username: string;
  }

  enum AuthStates {
    success = 'success',
    error = 'error'
  }

tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "allowUnreachableCode": false,
    "baseUrl": "./assets",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "jsx": "react",
    "lib": [
      "dom",
      "es2019",
      "esnext"
    ],
    "module": "commonjs",
    "moduleResolution": "node",
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "outDir": "./dist/",
    "resolveJsonModule": true,
    "skipDefaultLibCheck": true,
    "sourceMap": true,
    "strictPropertyInitialization": false,
    "strictNullChecks": true,
    "target": "es5",
    "typeRoots": [
      "./assets/definitions/types.d.ts",
      "./node_modules/@types"
    ],
    "types": [
      "node"
    ]
  },
  "include": [
    "./assets/src/**/*",
    "./assets/definitions/**/*"
  ],
  "exclude": [
    "node_modules"
  ]
}

我像這樣導入創建的接口:

import { Item, PlayableMedia } from 'seeyouftp';

該錯誤消息實際上非常具有誤導性,看起來像 typescript 錯誤。 似乎無法直接導出enums ,似乎有必要使用const才能正確導出它們。

所以我像這樣修改了我的enum聲明

declare module 'seeyouftp' {

  // exporting a const instead of 
  export const enum AuthStates {
    success = 'success',
    error = 'error'
  }
}

現在一切正常,但是該錯誤消息非常非常糟糕且耗時

嘗試導出聲明,看看是否有所不同:

declare module 'seeyouftp' {
export  interface User {
    admin: boolean;
    roles: string[];
    username: string;
  }

export  enum AuthStates {
    success = 'success',
    error = 'error'
  }

您需要在/definitions下創建seeyouftp (我假設seeyouftp是您的 js 模塊名稱)文件夾,並在/definitions/seeyouftp types.d.ts有 types.d.ts ,如下面的結構

|— definitions
 |—seeyouftp
  |— index.d.ts
|— entries
|— fonts
|— less
|— src

並更新您的tsconfig

"typeRoots": [
  "./assets/definitions",
  "./node_modules/@types"
],

因為它是 webpack 問題,所以您必須更新您的 webpack 配置。 Webpack 需要被告知在哪里可以找到模塊seeyouftp

// webpack.config.js
const path = require('path');

module.exports = {
  //...
  resolve: {
    // Add an alias
    alias: {
      'seeyouftp': path.resolve(__dirname, 'definitions/types.d.ts')
    }
  }
};

對於文件types.d.ts的路徑,我假設您的 webpack 配置位於definitions文件夾旁邊。

是相關的 webpack 文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM