58

I want to use: require.context('../images/', true, /\.(png|ico|svg|jpg|gif)$/)

but I get the following error:

Property context does not exist on type NodeRequire

Legends
  • 21,202
  • 16
  • 97
  • 123

3 Answers3

104

Just install the typings for webpack-env

npm i @types/webpack-env -D
Legends
  • 21,202
  • 16
  • 97
  • 123
20

And in tsconfig.json add it in the types property example:

 {
  "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
}
Ikhlak S.
  • 8,578
  • 10
  • 57
  • 77
JoaquinBu
  • 321
  • 2
  • 5
0

Besides the above solutions, you can also add an interface for this function manually just like this:

//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;
    }
}
RiverTwilight
  • 638
  • 4
  • 8