-
Notifications
You must be signed in to change notification settings - Fork 360
Description
Problem:
microbundle does not correctly bundling packages where the package type is "type": "module" in package.json
when importing const appfaker = require('@ekzemplo/common') the bundled package into a project which is using "type": "commonjs" this error id thrown:
node:internal/modules/cjs/loader:1125
throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
^
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /TST/ekzemplo/packages/ekzemplo-common/dist/index.js
require() of ES modules is not supported.
require() of /TST/ekzemplo/packages/ekzemplo-common/dist/index.js from /TST/ekzemplo/packages/ekzemplo-apievents/src/server.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /TST/ekzemplo/packages/ekzemplo-common/package.json.
...
this is the package.json of the imported package created with microbundle
{
"name": "@ekzemplo/common",
"version": "0.0.0",
"source": "./src/index.js",
"main": "./dist/index.js",
"module": "./dist/index.module.mjs",
"unpkg": "./dist/index.umd.js",
"exports": {
"import": "./dist/index.module.mjs",
"require": "./dist/index.js"
},
"type": "module",
"type":"commonjs",
"license": "MIT",
"scripts": {
"start": "microbundle watch",
"build": "microbundle build"
},
"dependencies": {
"faker": "^5.3.1"
}
}manual fix
I was able to fix the problem by renaming the file ./dist/index.js to ./dist/index.cjs and adapting main and require in the package.json after building:
{
"name": "@ekzemplo/common",
"version": "0.0.0",
"source": "./src/index.js",
"main": "./dist/index.cjs",
"module": "./dist/index.module.mjs",
"unpkg": "./dist/index.umd.js",
"exports": {
"import": "./dist/index.module.mjs",
"require": "./dist/index.cjs"
},
"type": "module",
"type":"commonjs",
"license": "MIT",
"scripts": {
"start": "microbundle watch",
"build": "microbundle build"
},
"dependencies": {
"faker": "^5.3.1"
}
}but this will break the next build!!
microbundle build
by creating files which end with .cjs.js - e.g. ./dist/index.cjs.js
Question
I am not an expert on the npm package format but would it be ok that in the case that the module type is "module" the ending of the generated files of main becomes .cjs or at least the names used in package.json are respected and not .js ist added if the name ends with .cjs