命名空间“global.Express”没有导出成员“Multer”

xar*_*lah 14 express nest multer

命名空间“global.Express”没有导出成员“Multer”。已经被这个错误困扰了两天了。我试过了:

  • 导入“穆特”
  • 从“multer”导入{ Multer }
  • 从“express”导入 { Express }
  • 添加 tsconfig 类型:[“Multer”]

但我的后端在构建时不断出错。

代码示例

小智 14

@types/multer我通过添加依赖项解决了同样的问题。

所以 yarn add @types/multer要么npm install --save @types/multer


Mic*_*ely 7

安装后npm install -D @types/multer,将“Multer”添加到文件中的compilerOptions-->types属性tsconfig.json

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "ES2021",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": false,
    "noImplicitAny": false,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false,
    "types": ["node", "Multer"]     // <-- Add "Multer" here
  }
}

Run Code Online (Sandbox Code Playgroud)

说明:在您的tsconfig.json文件中,可能"types"在 下指定了一个属性compilerOptions,根据此打字稿定义,如果types指定了该属性,则只有列出的包才会包含在全局范围中,因此,如果其中不包含“Multer”,它将不会不会自动包含在全局范围中,这就是为什么您会收到错误命名空间“global.Express”没有导出的成员“Multer”。

快捷破解:

警告:这只是使 Multer 在 Express 命名空间中可用的一种技巧,您应该确保类型可用于打字稿,就像我上面解释的那样。

import 'multer'; // a hack to make Multer available in the Express namespace

// ...

async createNewPost(
    // ...
    @UploadedFile() file: Express.Multer.File,
    // ...
)
Run Code Online (Sandbox Code Playgroud)

PS:在生产中,您可能需要出于不明原因@types/multer从移动devDependencies到。dependencies

PS2:如果您正在使用 nx.workspace,请确保编辑 Nest (API) 文件夹下 tsconfig.app.json 内的“类型”。

tsconfig.app.json

{
    "extends": "./tsconfig.json",
    "compilerOptions": {
        "outDir": "../../dist/out-tsc",
        "module": "commonjs",
        "types": ["node", "Multer"],    // <-- Add "Multer" here
        "emitDecoratorMetadata": true,
        "target": "es2015"
    },
    "exclude": ["**/*.spec.ts", "**/*.test.ts"],
    "include": ["**/*.ts"]
}
Run Code Online (Sandbox Code Playgroud)

  • 对我来说,将“multer”添加到 tsconfig.json 是有效的(注意开头的“M”)。 (2认同)