webpack-node-externals
webpack-node-externals copied to clipboard
Switch to ESM
Change the module from CommonJS to ECMAScript Module (ESM). Some JS Frameworks support ESM now and importing CommonJS modules may get complicated.
Just to clarify here... there's two ESM related things that are possible here:
- Switch this package to use ESM so that it's package.json contains
type: module - Update this package so that it doesn't assume all packages can be
require-ed in since node will freak out if yourequirean ESM npm package
Which of these were you describing with this ticket?
I'm trying to buld Google cloud functions with webpack with enabled ESM. But external modules added with webpack-node-externals are commonjs by default and webpack compiles them as:
/***/ "pino":
/*!***********************!*\
!*** external "pino" ***!
\***********************/
/***/ ((module) => {
module.exports = require("pino");
/***/ }),
As you can see webpack is dumb and uses require even if it's configured to output ESM module.
What webpack-node-externals options should I set to tell webpack that all externals should be imported as ES modules?
Used webpack-node-externals option importType: 'module' to pack my project with ESM support.
More details are here: https://github.com/nrwl/nx/issues/7872#issuecomment-997460397
importType: 'module' should be added to @types.
We'd like to use some CJS dependencies (e.g. lodash) and some ESM-only ones (like d3). Now my issue is that neither of the importType options work for us. When using the default importType: 'commonjs' I'm getting
module.exports = require("d3");
^
ReferenceError: require is not defined in ES module scope, you can use import instead
and with importType: 'module':
console.log((0,lodash__WEBPACK_IMPORTED_MODULE_2__.reverse)([(0,_util__WEBPACK_IMPORTED_MODULE_0__["default"])(), d3__WEBPACK_IMPORTED_MODULE_1__.scaleLinear().domain([3, 6])(4)]));
^
TypeError: (0 , lodash__WEBPACK_IMPORTED_MODULE_2__.reverse) is not a function
Without webpack-node-externals I can run the bundle without issues. Any ideas what do do in this case except downgrading the ESM-only packages to older, unsupported versions with CJS support?
@cbix I worked around the issue with this code:
importType: function( request ) {
if( request === '@errorx666/query' ) {
return `module ${request}`;
} else {
return `node-commonjs ${request}`;
}
}
More properly, the code should probably check package.json for type: module.