Wrangler throws error with package type module and webpack.config.js

When using module based development, i.e.

package,json

    "name": "mymodule",
    "type": "module"
}```

and a custom webpack.config.js:

new webpack.DefinePlugin({
PARTICLE: true
});

module.exports = {
target: “webworker”,
entry: “./index.js”,
mode: “production”
}


with a reference to the config in the wrangler.toml

name = “cloudparticle”
type = “webpack”
webpack_config = “webpack.config.js”


I get an error:

Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\sybla\WebstormProjects\particle\cloudparticle\webpack.config.js from C:\Users\sybla\AppData\Local.wrangler\wranglerjs-1.19.6\index.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 C:\Users\sybla\WebstormProjects\particle\cloudparticle\package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).


Following the directions in the error message to set the type to “commonjs” does not work for us because the code base is really designed for modern ECMA script. Obviously, we do not want to mess with the wrangler source from which the error it thrown. You might say “Well, transpile your modules first”; however, it is wrangler’s invocation of webpack to do the transpiling that is causing the issue. We need the custom webpack because we have compilation conditionals in the WebPack plugin.


Are there wrangler config options that can address this?

I would highly recommend that you join the Offical Cloudflare Discord. It is better for wrangler + workers questions. There are even members of the development teams there.

You’re trying to use ES Modules since you set "type": "module" in package.json however your Webpack isn’t compiling into ESM. If you just remove the type property, this will probably work

Ultimately got this working by reworking code so webpack define was not required.