Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use as es-modules for webpack config?

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?

like image 594
LongHike Avatar asked Dec 19 '19 10:12

LongHike


1 Answers

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)
    
like image 125
Thomas Avatar answered Sep 17 '22 02:09

Thomas