What is the process for importing map-obj?

When attempting to incorporate this library, I encountered 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]: The usage of require() with an 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 is not supported.
Instead, modify the require statement for index.js in /Users/alexs/Documents/projects/xml-controller-test/dist/app.controller.js to utilize 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 am hesitant to make any major alterations to my package.json that could disrupt the project. Although I did try adding "type": "module" to package.json, unfortunately, it did not resolve the issue.

ReferenceError: exports is not defined in ES module scope
This file is being treated as an ES module due to its '.js' file extension and '/Users/alexs/Documents/projects/xml-controller-test/package.json' containing "type": "module". To treat it as a CommonJS script, rename it with the '.cjs' file extension.

This is how I currently implement it:

import mapObject, { mapObjectSkip } from 'map-obj';

My configuration includes basic nestjs package.json and tsconfig.json files. Is there a method to import this library into a TS project successfully?

The compilation process seems to be where the issue lies. It's surprising that the functionality depends on this setup. Here is an approach I recently attempted:

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

However, now I am encountering this problem:

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/xml-parser.interceptor.js is not supported.
Modify the require statement for index.js in /Users/alexs/Documents/projects/xml-controller-test/dist/xml-parser.interceptor.js to use dynamic import() instead, which is available in all CommonJS modules.
    at /Users/alexs/Documents/projects/xml-controller-test/dist/xml-parser.interceptor.js:13:30
tsconfig.ts
{
  "compilerOptions": {
    // Configuration details
  }
}
package.json
{ 
  // Package information and scripts
}

The import statement used is

import mapObject, { mapObjectSkip } from 'map-obj';

For testing purposes, here is how I'm utilizing it:

    mapObject(body, (key: string, value) => [key.toLowerCase(), value], {
      deep: true,
    });

Answer №1

Incorporating an ES module into a CommonJS project is not achievable through the use of require(). However, it can be done by utilizing dynamic import. It's important to note that this differs from the static import method recommended by Borodin.

You have a couple of options for achieving this:

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

...or you can utilize await within an asynchronous function like so:

async function someAsyncFunction() {
  const { default: mapObject, mapObjectSkip } = await import('map-obj')
}

Answer №2

Perhaps the correct method is as follows:

import map_obj_1 from "map-obj"

Seems like a similar problem

tsconfig

{
  "compilerOptions": {
    "module": "nodenext"
  },
  "include": ["*.ts"]
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Node Js for Form Data Transmission and Retrieval

I've successfully created two separate JS files, each responsible for sending and retrieving form data to and from the database. My dilemma is whether it's more practical or feasible to leave these two JS files as they are and serve their individ ...

There seems to be an issue with the vue-cli when attempting to build in

Within my project files, there is a .env file present -public -src -.env.development.local In the package.json file, it contains: { "name": "my-website", "version": "0.1.0", "scripts": { ...

What is the mechanism behind pushing an empty array into another empty array?

let arr = []; console.log(arr.push([])); // 1 Instead of logging [[]], the output is 1. Can someone explain what is happening in the code above? ...

WikiQuote API signals successful batch access

Currently tackling the API challenges on freeCodeCamp and the first one has me feeling a bit lost, especially since I am still a beginner. For this challenge, I'm utilizing wiki quotes with my endpoint being . Below is the code that I have drafted: $ ...

Managing ajax requests timeouts while abiding by the browser's connection limitations

Encountering an issue with ajax requests and fixed timeouts, I've resorted to using this straightforward code snippet: $.ajax({ url: "test.html", error: function(){ //do something }, success: function(){ //do something ...

What is the reason why Prettier does not automatically format code in Visual Studio Code?

After installing and enabling ESLint and Prettier in my Nuxt application, I made the switch to Visual Studio Code. However, when I open a .vue file and use CMD+ Shift + P to select Format Document, my file remains unformatted. I even have the Prettier ex ...

Exporting a variable that is currently in use within a function being exported

I am currently working on setting up my mongodb in a separate file. I have created an initialization function where I write all the necessary code for connecting to the database and exporting the function. However, I also need to export the 'db' ...

Allow the button to be clicked only when both options from the 1/3 + 1/3 radio buttons are selected

How can I ensure that the next <button> at the bottom of the HTML is only clickable when at least one of each <input type="radio"> is checked? Also, how do I integrate this with my current function? The button itself triggers a jQuery function ...

What is the best way to incorporate node modules into my tsconfig file?

I've taken some raw angular typescript components and packaged them into a private NPM module for sharing between various projects. Although I import these components like any other npm library, I encounter an error message when trying to serve my ap ...

React displays the previous state

Can someone assist me with the code provided below? import React, { useState, useEffect } from 'react'; import { Container, Row, Col, ListGroup, Button, InputGroup, FormControl } from 'react-bootstrap'; import FileUpload from './C ...

Unexpected outcome in Typescript declaration file

This code snippet is dealing with the 'legend' function: legend = (value) => { return typeof value === 'boolean' ? { 'options.legend.display': value } : { 'options.l ...

Is it possible that using the component getter to display a router link may not be effective?

My email application is being developed using angular 6, featuring a list of mailboxes for users to access by clicking on the provided link. Interestingly, when utilizing component version A to display the mailbox list, clicking on the router link does no ...

Exploring the source code of NPM public and private packages within the node_modules directory

As someone who is new to javascript development, I want to create a private npm package that cannot be accessed by users. However, I have noticed that I can still view the code of other npm packages labeled as closed-source by entering their node_modules s ...

When a Vue.js Directive is inserted or bound, it actually takes precedence over the click event

Imagine having multiple dropdowns or elements on the page that all utilize a directive called "closable". This directive triggers an expression if the element clicked is outside of the element using the directive. The intended behavior is that when clicki ...

Exploring nullish coalescing with undefined values

My function is set up to make API calls: interface getEventsPropsShape { eventId?: string; accountId?: string; eventsStartAfter?: string; } const getEvents = async ({ eventId, accountId, eventsStartAfter, }: getEventsPropsSha ...

Ways to return to a previously active div when clicking the back link on a webpage

My approach involves toggling between different divs when clicking on links. Each div contains its own form which submits data to a new page, and then I use a "go back" link to return to the previous page. However, the issue arises when the active div at ...

Tips for integrating AudioWorklets with vue-cli, webpack, and babel (resolved illegal invocation error)

I'm experiencing some challenges while attempting to develop a WebApp using vue-cli with AudioWorklets. Whenever I try to access properties of my AudioWorkletNode, such as port or channelCount, I encounter multiple errors: TypeError: Illegal invocati ...

What is the best way to retrieve a specific value from a set of elements that share the same name?

My dilemma lies in handling two radio buttons that share the same name but have different values. I need to ensure that the correct value is selected before allowing the form to be submitted, and prompt the user if an incorrect selection is made. Below is ...

Stopping a Javascript function from running when an asp.net webform is loaded

Here is the code I wrote to display my position on the map: <script src="http://maps.googleapis.com/maps/api/js"></script> <script> function initialize(x, y) { alert(x); alert(y); var mapProp ...

Facing a 404 error with react-router while manually typing in the URL

I've encountered an issue with my project. Everything was working fine with createBrowserRouter until I deployed it. When I manually enter the URL, I get a 404 error for all pages except the landing page. Below is a snippet of my code: main.jsx impo ...