16

I am using node 13.4.0. with es modules (via .mjs extensions).

Using webpack config files as es modules crashes:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /path-to-config-dir/webpack.config.mjs

Simplest es module webpack.config.mjs:

export default {};

Does webpack support es-modules for config files? I couldn't find a lot of information on that topic. I've found this (an issue closed in June 2019):

https://github.com/webpack/webpack/pull/9226

So I am wondering about the state of webpack config files regarding mjs. Can anybody point me to some documentation on this?

LongHike
  • 4,016
  • 4
  • 37
  • 76

1 Answers1

6

I'm using Node v14.16.0 and Webpack 5.37.0. Although it's not documented, a configuration file named webpack.config.mjs seems to be picked up automatically, and is interpreted as a module.

Some caveats though:

  • import { Something } from 'webpack' does not work. Use this instead:

      import webpack from 'webpack'
      const { Something } = webpack
    
  • __dirname is frequently used in Webpack configs, but isn't available in a module. To bring it back:

      import path from 'path'
      const __dirname = path.dirname(new URL(import.meta.url).pathname)
    
Thomas
  • 174,939
  • 50
  • 355
  • 478
  • Though it's a while ago, I've asked this question, this makes for a good answer. I like the __dirname solution in particular. Quite nice! – LongHike Jun 22 '21 at 18:16
  • Note: This is not entirely correct. To replace `__dirname` use `import { fileURLToPath } from 'url';const __dirname = fileURLToPath(import.meta.url);` and replace `module.exports` with `export`. See: https://github.com/nodejs/node/issues/28114 – Startec Jan 29 '22 at 10:15
  • Make that `const __dirname = path.dirname(fileURLToPath(new URL(import.meta.url)))` – Startec Jan 29 '22 at 10:21