Build Issue with CommonJS Version After Updating to choices.js v11 #1250
Closed
Description
Describe the bug
Our library supports both CommonJS (cjs) and ES Module (esm) builds. We are currently trying to update choices.js to v11 but are facing a build issue with the cjs version.
To Reproduce
Steps to reproduce the behavior:
- Go to StackBlitz example.
- Run
npm run build:cjs
andnpm run serve
commands. - Inspect the console.
- See the error:
Uncaught TypeError: choices_js_1.default is not a constructor
.
This issue can also be reproduced with Node.js, as it uses cjs by default:
- Install the latest version of choices.js.
- Create an
index.js
file and try to import choices:const Choices = require('choices.js');
. - Run
node index.js
. - See error
main.js:1
const Choices = require('choices.js');
^
Error [ERR_REQUIRE_ESM]: require() of ES Module demo\node_modules\choices.js\public\assets\scripts\choices.js from domo\main.js not supported.
choices.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 either rename choices.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 demo\node_modules\choices.js\package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).
Expected behavior
We should be able to import choices.js and use it with cjs modules.
Choices version and bundle
- Version: [e.g. v11.0.3]
Additional context
It looks like the problem is in the type: "module"
declaration in the package.json. The issue is resolved if the type: "module"
is removed in local version of choices.js, as the package.json contains both module and main entry points.