I’m trying to import this lib and I get the following error:
/Users/alexs/Documents/projects/xml-controller-test/dist/app.controller.js:20
const map_obj_1 = require("map-obj");
^
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/alexs/Documents/projects/xml-controller-test/node_modules/map-obj/index.js from /Users/alexs/Documents/projects/xml-controller-test/dist/app.controller.js not supported.
Instead change the require of index.js in /Users/alexs/Documents/projects/xml-controller-test/dist/app.controller.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (/Users/alexs/Documents/projects/xml-controller-test/dist/app.controller.js:20:19)
I wouldn’t like to make any significant changes in my package.json that would the project. Though, I tried adding "type": "module" to package.json, it didn’t help.
ReferenceError: exports is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/Users/alexs/Documents/projects/xml-controller-test/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
The way I do it:
import mapObject, { mapObjectSkip } from 'map-obj';
I have a basic nestjs package.json
and tsconfig.json
files.
Is there any way to import this library in a TS project?
2
Answers
It seems that the proper way should be:
Looks like similar issue
tsconfig
You are importing an ES module into a CommonJS project. This is not possible using
require()
, however it is possible usingdynamic import
. Note, this is not the same asstatic import
suggested by Borodin.You can do it using callbacks:
…or using await inside an asynchronous function