skip to Main Content

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


  1. It seems that the proper way should be:

    import map_obj_1 from "map-obj"
    

    Looks like similar issue

    tsconfig

    {
      "compilerOptions": {
        "module": "nodenext"
      },
      "include": ["*.ts"]
    }
    
    Login or Signup to reply.
  2. You are importing an ES module into a CommonJS project. This is not possible using require(), however it is possible using dynamic import. Note, this is not the same as static import suggested by Borodin.

    You can do it using callbacks:

    import('map-obj').then(m => {
      const mapObject = m.default
      const mapObjectSkip = m.mapObjectSkip
    })
    

    …or using await inside an asynchronous function

    async function someAsyncFunction() {
      const { default: mapObject, mapObjectSkip } = await import('map-obj')
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search