2
votes

I'm trying to use ES imports in my Webpack configuration file, but I'm not getting Node to accept them.

webpack.config.js:

import webpack from 'webpack';

export default {
  mode: 'development'
};

And in package.json:

{
  "scripts": {
    "start": "node --experimental-modules node_modules/webpack-dev-server/bin/webpack-dev-server.js"
  }
}

However, when I try to run it using npm start, I get the following error:

C:\redacted\webpack.config.js:1
import webpack from 'webpack';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1072:16)
    at Module._compile (internal/modules/cjs/loader.js:1122:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Module.require (internal/modules/cjs/loader.js:1044:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at WEBPACK_OPTIONS (C:\redacted\node_modules\webpack-cli\bin\utils\convert-argv.js:114:13)
    at requireConfig (C:\redacted\node_modules\webpack-cli\bin\utils\convert-argv.js:116:6)
    at C:\redacted\node_modules\webpack-cli\bin\utils\convert-argv.js:123:17

What am I doing wrong? How can I make it respect the --experimental-modules flag and allow the import statement?

Relevant versions:

  • Node: 12.16.1
  • npm: 6.13.4
  • webpack: 4.41.8
  • webpack-cli: 3.3.11
  • webpack-dev-server: 3.10.3
1

1 Answers

0
votes

Based on the NodeJS docs, Node will treat files as ES modules when

  • Files with ends with a .mjs extention
  • Files ending in .js when the nearest parent package.json file contains a top-level field type with a value of module.