Tips for selecting 'module' over 'main' in package.json

I have developed several npm modules and compiled them in two ways:

  • commonJS (using exports.default =) and
  • esm (using export default)

In my package.json, I have specified the main file as index.cjs.js and the module file as index.esm.js.

However, when I install the package and try to import it like this:

import myPackage from 'my-package'

It always chooses the main file, not the module.

My question:

Is there a way to import the module file instead of the main file when doing

import myPackage from 'my-package'
in a JavaScript file?

Reason for setting commonJS file as "main":

I have observed that when working with Node, importing an esm file using export default is not feasible. Therefore, I have chosen the commonJS format for the "main" path in package.json to make it accessible to a wider audience.

Explanantion for defining a separate "module" in package.json:

Many popular libraries like Vue.js follow this practice. More information can be found on this Stackoverflow thread:

What is the "module" package.json field for?

Reason for wanting to import the "module" file instead of the "main" file:

There is a known bug in Rollup where it does not correctly display JSDoc comments after importing a cjs file, but it works fine with an es file.

Avoiding the workaround:

One possible solution is to set "main" to the esm file in package.json. However, this would prevent users utilizing my packages in Node apps from using it.

→I am somewhat perplexed by all of this, but after conducting thorough research, I believe I have a good understanding. If anyone has a better approach or any advice, please share it in the comments below!

Answer №1

Simply avoid using an extension for the main file and create two separate files in the same directory with different extensions - one for ES6 and one for CommonJS. For example:

index.js // CommonJS code for older versions of Node.js
index.mjs // ES6 module syntax

Then in your package.json:

{
  "main": "index"
}

When Node.js is launched with the --experimental-modules flag, it will use the *.mjs file, otherwise it will use the *.js file.

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

Problem encountered while packaging in .gitlab-ci

Currently, I am attempting to set conditions in my .gitlab-ci.yml file. If a package does not exist, then npm will publish and pack the library in the GitLab registry. Although I have granted my pipeline permission to access the registry and provided the n ...

Encountering an issue during the installation of the pg node module

Having trouble installing the pg node module due to this error: Exception: Call to 'pg_config --libdir' returned exit status 1. while trying to load binding.gyp gyp ERR! configure error gyp ERR! stack Error: `gyp` failed with exit code: 1 gyp ER ...

The main content will be displayed on the sub-routes of the child

I'm feeling uncertain about the routes for children. For example, I have an 'About' route with 'me' as a sub-route: { path: '/about', name: 'About', component: About, children: [ { ...

Send an object to query when using Router.push in Next.js

Just getting started with NextJs and I'm experimenting with passing an object to another page through a component. Let me show you the code and explain what I'm attempting to accomplish: The object I want to pass looks like this: objectEx = { ...

Tips for inserting SVG images into PDF documents

Is there a way to generate a PDF upon clicking the "generate PDF" button? The PDF should display an image containing highlighted squares corresponding to the user's selections on the webpage. I've been struggling to include the SVG in the PDF as ...

Determine in React whether a function returns a true value, and execute the code for false regardless

I have a hunch that this is related to the concept of asynchronicity. Essentially, I'm trying to validate whether a string (an answer to a question) already exists. If it does, the page should just show a message; otherwise, it should add the new que ...

JavaScript library that provides SQL-like functionality for easily manipulating arrays

After successfully parsing a csv file into an array of objects, I find myself in need of making multiple alterations to that array. Currently, I am utilizing lodash methods for this task, but I am finding it to be quite verbose. I am considering working wi ...

Clickable link unresponsive on parallax-enhanced webpage

Currently, I am utilizing Zurb foundation's Manifesto theme for creating a parallax scrolling landing page. The anchor tag is essential for the scrolling effect on this page, causing a conflict when regular anchor links are included. Here is the HTML ...

I am endeavoring to send out multiple data requests using a function, ensuring that the code execution occurs only once all the results have been received

After reading through a post on Stack Overflow about handling multiple AJAX calls in a loop (How to take an action when all ajax calls in each loop success?), I was able to come up with a solution. I decided to track the number of requests I needed to make ...

What is the best way to structure JavaScript files in Rails 3?

I am currently developing a web application in Rails 3 and have opted to use JQuery as my primary Javascript framework. While my application doesn't have an extensive amount of Javascript at the moment, I am starting to incorporate transitions between ...

What is the process for displaying the attributes of a custom object in Typescript?

I need help returning an array of prop: value pairs for a custom object using the myObject[stringProp] syntax. However, I keep encountering this error message: TS7053: Element implicitly has an 'any' type because expression of type 'str ...

The function res.sendFile() seems to be unresponsive

While building my server-side application using node.js, express, and request-promise, I encountered an issue with the res.sendFile() function in my server.js file. Despite including res.sendFile(__dirname + '/public/thanks.html'); within a .then ...

Exploring the Power of Jest and Vue Test Utils for Unit Testing in VueJS

Having recently started Unit Testing with vue, I am currently working on unit testing a navigation vue component. My initial goal was to test a method that simply sets a boolean value to false upon clicking. Utilizing vuetify, I attempted to replicate a bu ...

Receiving errors while using `npm install` due to gyp verb issues

Whenever I use npm, it usually runs smoothly. However, today when I tried to run it in a folder that contains a package.json file with dependencies, I encountered some errors after about 10 seconds: npm ERR! code 1 npm ERR! path C:\Users\USER&bso ...

NodeJs and React do not automatically refresh files when using https protocol

I'm facing a frustrating issue that I just can't seem to crack... No matter what I try, I can't figure out why when I access the application through IP:3000, it loads updated files perfectly fine. But when I try to access it via , it refuse ...

Upon concatenation, the screen automatically returns to the beginning of the page

I've set up a page with a list of items, and at the bottom there's a handy "Load more" button that fetches new items to add on top of the existing list: handleLoadProducts = (append = false) => { this.setState({ isLoading: true, ...

A Great Option for Easy Drag and Drop Functionality

Currently researching options for Drag and Drop functionality with items such as images and textareas. Need a solution that provides coordinates of where the item is dropped on screen, saves it, and allows placement in the exact same location later. Desir ...

Utilize JQuery's .load() function to transmit JSON data to your Flask server

I am attempting to utilize JQuery's .load() function in order to transmit data to my Flask server and then, with that information, display a <div> that is loaded into the element making the request. This is what my code snippet looks like: $(&qu ...

Creating Unique Numbers for Every <a> Element

Can someone help me figure out how to create a form that generates a unique set of random numbers from the range (0,9) displayed in a group of button tags? I've written some javascript code but it's not quite working as intended. (function($) ...

Implementing HTML page authentication with Identity ADFS URL through JavaScript

I have a basic HTML page that displays customer reports using a JavaScript function. The JavaScript makes an ajax call to retrieve the reports from a backend Spring REST API. In the Spring REST API, I have set up an endpoint "/api/saml" for authentication ...