Skip to content

Error when importing CommonJS module #156

@nagyszabi

Description

@nagyszabi

Hi there!

When working with node-opcua-xml2json which uses ltx, I encounter the following error:

Error [ERR_REQUIRE_ESM]: require() of ES Module /snapshot/backend/node_modules/ltx/lib/parsers/ltx.js from /snapshot/backend/node_modules/node-opcua-xml2json/dist/source/xml2json.js not supported.
ltx.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 ltx.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 /snapshot/backend/node_modules/ltx/package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).

    at Module.require (pkg/prelude/bootstrap.js:1851:31)
    at Object.<anonymous> (/snapshot/backend/node_modules/node-opcua-xml2json/dist/source/xml2json.js:12:19)
    at Module._compile (pkg/prelude/bootstrap.js:1930:22) {
  code: 'ERR_REQUIRE_ESM'
}

Node.js v20.11.1

Because node-opcua-xml2json is compiled into CommonJS, it uses the compiled CommonJS version of the ltx parser.
But node thinks that it is an ESM module, because the package.json in the root of the project specifies "type": "module".

In my testing I found that changing "type": "module" to "type": "commonjs" fixes this issue.

I saw that the lib folder has another package.json file which has it's type set to "commonjs", but node20 does not seem to pick it up when working with node-opcua-xml2json.

I think changing the package.json in the root folder would be ideal, because it would still work the way it does right now.
In addition according to this source specifying the main ESM entry point using "module" is not standard in node, and only "main" is officially supported. And since "main" is set to lib/ltx.js and type is set to module, it thinks that the compiled js is actually ESM instead of CommonJS.

One more thing that would make it super clear to node where each type of files are, would be to use package exports, more specifically conditional exports.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions