Gabuardi
Gabuardi

Reputation: 63

ESM import on webpackConfig

I'm building a webpack app and I'm interested in use ESM through the entire app, meaning that build the webpack.config file with ESM imports.

I now this is possible using Babel, but this was before npm added the "type": "module" supporting now ESM imports without babel... I already tried it with Express and it worked but with Webpack I get this:

> ...proyectDirectory/node_modules/webpack-cli/bin/cli.js:93

> require() of ES modules is not supported.

So I was wondering if there is a version of webpack-cli that use import instead of require

Upvotes: 6

Views: 11764

Answers (2)

fregante
fregante

Reputation: 31698

Update to at least webpack-cli 4.5.0. Support for native ESM configuration files has just been added: https://github.com/webpack/webpack-cli/releases/tag/webpack-cli%404.5.0

This means that if you're using webpack.config.js in a directory with {"type": "module"} in its package.json, it will work.

It will also work if you simply name your file webpack.config.mjs

Upvotes: 6

cyberwombat
cyberwombat

Reputation: 40084

Webpack CLI is expecting a commonJS file. There is experimental support for .mjs file that can be enabled using the experiments.mjs flag but it seems there are a number of issues around that. So you can use webpack by using either no config or using a .cjs config as:

 ./node_modules/.bin/webpack-cli --config webpack.config.cjs

Also keep in mind that things like Jest do not work with esm (as of this date) so you'd need to use another test suite if no babel/esm was desired.

Upvotes: 1

Related Questions