typescript webpack -类型NodeRequire上不存在属性上下文

w80xi6nr  于 2023-01-31  发布在  TypeScript
关注(0)|答案(3)|浏览(238)

我想使用:require.context('../images/', true, /\.(png|ico|svg|jpg|gif)$/)
但我得到了以下错误:
类型NodeRequire上不存在属性上下文

7bsow1i6

7bsow1i61#

2018年的解决方案:

只需安装webpack-env的类型

npm i @types/webpack-env -D
tcbh2hod

tcbh2hod2#

在tsconfig.json中,将其添加到types属性示例中:

{
  "compilerOptions": {
    "outDir": "./dist/",
    "declaration": true,
    "declarationDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": false,
    "module": "commonjs",
    "target": "es6",
    "allowJs": false,
    "types": [
      "node",
      "webpack-env" // here
    ]
  },
  "files": [
    "src/index.ts"
  ],
  "compileOnSave": false
}
rjee0c15

rjee0c153#

除了以上解决方案外,您还可以手工为该功能增加一个接口,如下所示:

//index.d.ts

declare global {
    interface NodeRequire {
        /** A special feature supported by webpack's compiler that allows you to get all matching modules starting from some base directory.  */
        context: (
            directory: string,
            useSubdirectories: boolean,
            regExp: RegExp
        ) => any;
    }
}

相关问题