Legends
Legends

Reputation: 22692

webpack - Property context does not exist on type NodeRequire

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

Upvotes: 64

Views: 29400

Answers (3)

Legends
Legends

Reputation: 22692

Just install the typings for webpack-env

npm i @types/webpack-env -D

Upvotes: 121

RiverTwilight
RiverTwilight

Reputation: 726

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;
    }
}

Upvotes: 2

JoaquinBu
JoaquinBu

Reputation: 401

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
}

Upvotes: 28

Related Questions