What is the best way to create an ESM / CJS module without needing to include '.default' in the imports?

Is it possible to configure my package.json to support different imports for CJS and ESM formats?

  "main": "dist/cjs/index.js",
  "module": "dist/esm/index.js",

In addition, can I set up my TypeScript compiler to generate two distributions:

// for ESM
{
  "compilerOptions": {
    "module": "es2020",
    "target": "es2015",
    "declaration": true,
    "esModuleInterop": true,
    "moduleResolution": "node",
    "forceConsistentCasingInFileNames": true,
    "outDir": "./dist/esm"
  },
  "include": [
    "src/**/*"
  ]
}
// for CJS
    "extends": "./tsconfig.json",
    "compilerOptions": {
        "module": "CommonJS",
        "outDir": "./dist/cjs"
    },

By running both configurations through tsc, a dist folder containing both the cjs and esm folders can be created:

"build": "tsc -p tsconfig.json && tsc -p tsconfig-cjs.json"

However, the testing reveals that I need to add .default in both examples:

// CJS
const someClass = require('package').default
const instance = new someClass()

// ESM
import someClass from 'package'
const instance = new someClass.default("")

How can I eliminate the requirement of adding .default in both instances?

The package exports just a single class:

import someClass from './class';

export default someClass;

This is how the class is defined:

class someClass { constructor() {} }

export default someClass

Answer №1

To export without default, you must use a specific syntax:

class anotherClass { constructor() {} }

export = anotherClass

(To import this export in a TypeScript project, make sure to enable the esModuleInterop flag.)

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

How can we dynamically render a component in React using an object?

Hey everyone, I'm facing an issue. I would like to render a list that includes a title and an icon, and I want to do it dynamically using the map method. Here is the object from the backend API (there are more than 2 :D) // icons are Material UI Ic ...

Looking for an instance of a node.js ftp server?

I'm facing a challenge in creating a node.js application that can establish a connection with an FTP server to download files from a specific directory: Despite attempting to follow the instructions provided in the documentation for the ftp npm packa ...

Invoke a function in Angular when the value of a textarea is altered using JavaScript

Currently, I am working with angular and need to trigger my function codeInputChanged() each time the content of a textarea is modified either manually or programmatically using JavaScript. This is how my HTML for the textarea appears: <textarea class ...

Selecting any of the bar chart labels will reveal just a two-day timeframe

My bar chart is behaving strangely - when I click on all labels, it only shows two days instead of updating as expected. I suspect it may be due to a bad implementation involving parsing. Can anyone provide assistance? I have created a minimum example on ...

Unable to remove a OneToMany entry in TypeORM

I am currently working with the following database schemas: @Entity() export class Question extends BaseEntity { @PrimaryColumn() messageId: string; @Column() authorId: string; @Column() question: string; @Column("varchar", { arr ...

Having trouble uploading a file in PDF format (*.pdf)

I'm attempting to use Node's readFile method to read a file and then send it as a response so that the user can download it. This is the code snippet I have: async function(req, res, next) { const query = { id: req.params.id }; // @ts-ignore co ...

"Encountered an error in Angular: ContentChild not found

Working with Angular 5, I am attempting to develop a dynamic component. One of the components is a simple directive named MyColumnDef (with the selector [myColumnDef]). It is used in the following: parent.compontent.html: <div> <my-table> ...

The subsequent picture is not appearing on screen

I'm encountering an issue with my Shadcn UI carousel where the images are not being displayed, even though the controls fit into the screen. Interestingly, when I replace the property fill with width and height values, the images show up. Here's ...

Retrieving Information from an Angular 2 Component

Struggling to figure this out, I am attempting to dynamically add user video data that includes a video URL. My goal is to access the data from the component so I can use it in my HTML. I've attempted the following approach. app.component.ts import ...

Using computed properties with Nuxt's `head` property can result in error messages being displayed

While utilizing Nuxt.js, I am using head() { } method to configure SEO metadata. However, when accessing computed properties within this method, Vetur displays the following message: Property 'domain' does not exist on type 'CombinedVueInst ...

Unpacking data types from an array of classes in TypeScript: A step-by-step guide

I am working on a function that takes an array or rest of Typescript classes as input and resolves, returning their instances. However, I'm struggling to ensure correct typing for it. If I take one class as an example: class Base { isBase = true ...

Converting an Observable containing an Array of StaffInterface objects to a plain Array of StaffInterface objects in @ngrx/store select

Trying to retrieve an Array<StaffInterface> from an Observable<Array<StaffInterface>> in ngrx store.select. The store.select method returns the Observable<Array<StaffInterface>>, which I then need to convert into an Array<S ...

The creation of a Firebase user account with the specified email and password

I'm currently facing an issue while creating a new user with email and password using firebase authentication. The problem arises when I try to access the displayName from the returned async call before the updateProfile function, as it returns a null ...

Does moment/moment-timezone have a feature that allows for the conversion of a timezone name into a more easily comprehendible format?

Consider this example project where a timezone name needs to be converted to a more readable format. For instance: input: America/Los_Angeles output: America Los Angeles While "America/Los_Angeles" may seem human-readable, the requirement is to convert ...

prolonging inner interface created by supabase

Below is the Typescript interface that has been generated by Supabase export interface definitions { Users: { /** Format: uuid */ id: string; /** * Format: timestamp with time zone * @default now() */ created_at?: string; ...

How to manage type mappings while utilizing the spread syntax

In my testing scenario, I am utilizing a setup function and I am looking for a way to pass typing information along when it is called so that I can benefit from intelligence support without having to bypass it in eslint. function setup(): SomeType { retu ...

Employing angular-ui-bootstrap to display pop-up notifications

I am new to using Angular and TypeScript and I am attempting to create a popup when an image is clicked. I came across a post on Stack Overflow that provides a solution using IMODALSERVICE. How to utilize angular-ui-bootstrap modals with TypeScript? Howe ...

Filtering server-side components in Next.js to create a customized list

Having been accustomed to the previous architecture of Next.js, I embarked on a new project where I am exploring the use of server and client components in the latest architecture. Specifically, I have a page dedicated to displaying race results in a tabl ...

JavaScript has a feature called "functions" which allow the declaration of named blocks of

Currently, I am developing an Electron app in typescript. In my main.ts file, I have instantiated a custom CommunicationProvider class object. What I want is for this class to declare multiple methods (specified in an interface that it implements) but have ...

Step-by-step guide on building a wrapper child component for a React navigator

When using the Tab.Navigator component, it is important to note that only the Tab.Screen component can be a direct child component. Is there a way in Typescript to convert or cast the Tab.Screen Type to the TabButton function? const App = () => { retur ...