Skip to content

[Bug] ESM require error importing webpack config #128

@rbtcollins

Description

@rbtcollins
  • I'd be willing to submit the fix

Describe the bug

I have some ES module based code I wanted to test. Mocha works, but the mochapack features sounded nice, so went to try it.

First hurdle was the requirement to set ecma on the terser plugin, as 'npm exec mochapack' was throwing an error from terser.

So I created a webpack config:

$ cat webpack.config.js 
const TerserPlugin = require("terser-webpack-plugin");

module.exports = {
    optimization: {
        minimize: true,
        minimizer: [new TerserPlugin({
            terserOptions: { ecma: 2020 }
        })],
    },
};

That got past terser, and then it throws in mochapack:

$ npm exec mochapack
<root>\node_modules\mochapack\lib\cli\argsParser\optionsFromParsedArgs\webpack\requireWebpackConfig.js:139
        config = require(requirePath); // eslint-disable-line global-require, import/no-dynamic-require
                 ^

Error [ERR_REQUIRE_ESM]: require() of ES Module <root>\webpack.config.js from <root>\node_modules\mochapack\lib\cli\argsParser\optionsFromParsedArgs\webpack\requireWebpackConfig.js not supported.
webpack.config.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules.
Instead rename webpack.config.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change "type": "module" to "type": "commonjs" in <root>\package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).

mochapack was installed with ```npm installafter settingtype:'module'` in package.js.

To Reproduce

Sorry, this is a drive by, though if you can't trivially reproduce I can upload something after the semester ends.

Screenshots

If applicable, add screenshots to help explain your problem.

Environment if relevant (please complete the following information):

  • OS: Windows
  • Node version 17.7.2
├── chai@npm:@esm-bundle/chai@4.3.4-fix.0
├── handlebars@4.7.7
├── mocha@9.2.2
├── mochapack@2.1.4
├── terser-webpack-plugin@5.3.1
├── ts-node@10.7.0
└── webpack@5.70.0

Additional context

Add any other context about the problem here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions