webpack: require.context is not a function is ESM (type: module)

What is the current behavior?

If we have ES module (example):

const context = require.context(
  "./icons",
  true,
  /^[.\\/a-zA-Z\d-]+\.svg$/,
  "sync"
)

export const icons = context
  .keys()
  .map(context)
  .map(m => m.default)

and the nearest package.json contains {"type": "module"} then while a build we get the error:

require.context is not a function

If to remove {"type": "module"} in package.json there will be no error, build is ok.

If the current behavior is a bug, please provide the steps to reproduce.

webpack version: 5.72.0 Node.js version: 16 Operating System: Windows 10

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 22 (14 by maintainers)

Most upvoted comments

@alexander-akait What you mean by import(..)? What is the replacement for require.context in ESM?

Here I found https://webpack.js.org/api/module-variables/#importmetawebpack

I tried to use import.meta.webpackContext but got the error: {}.webpackContext is not a function

require.context doesn’t exit in ESM, please use import(...)

I think we should throw an error on empty import.meta.webpackContext()

@alexander-akait Yes I see this in docs)) it works ok now. It is just misleading webpack error.