Babel plugin and helper functions for interoperation between Node.js native ESM and Babel ESM

Overview

babel-plugin-node-cjs-interop and node-cjs-interop: fix the default import interoperability issue in Node.js

The problem to solve

Consider the following modules:

// a.js

export default function greet() {
  console.log("Hello, world!");
}
// b.js

import greet from "a.js";

greet();

They usually work, unless the following conditions are met:

  • a.js (the module being imported) is a simulated ESM. That is, the module is transpiled as a CommonJS module (by Babel or TypeScript) before execution. And,
  • b.js (the importing module) is a native ESM, That is, the module is run on Node.js' native ES Module support.

You can reproduce the above condition by placing the following files:

// a.cjs

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = greet;

function greet() {
  console.log("Hello, world!");
}
// b.mjs

import greet from "./a.cjs";

greet();
$ node ./b.mjs
./b.mjs:3
greet();
^

TypeError: greet is not a function
    at ./b.mjs:3:1
    at ModuleJob.run (node:internal/modules/esm/module_job:185:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:281:24)
    at async loadESM (node:internal/process/esm_loader:88:5)
    at async handleMainPromise (node:internal/modules/run_main:65:12)

Solution 1: Babel plugin

Install the babel plugin:

npm install -D babel-plugin-node-cjs-interop
# or:
yarn add -D babel-plugin-node-cjs-interop

Configure it in your Babel configuration:

// .babelrc.js or babel.config.js

export default {
  presets: [/* ... */],
  plugins: [
    // ...
    [
      "babel-plugin-node-cjs-interop",
      {
        packages: [
          "styled-components",
          "@babel/helper-plugin-test-runner",
        ],
      },
    ],
  ],
};

See the package's README for details.

Solution 2: manually inserting the wrapper

npm install -D node-cjs-interop
# or:
yarn add -D node-cjs-interop
import styledOrig from "styled-components";
import { interopImportCJSDefault } from "node-cjs-interop";

const styled = interopImportCJSDefault(styledOrig);

See the package's README for details.

Comments
Owner
Masaki Hara
Software Engineer at @wantedly
Masaki Hara
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Um bot de suporte feito usando threads para o Discord, 100% customizável, feito em JavaScript e inspirado no Rio Helper do servidor Elixir Lab e na Loritta Helper do serivdor de suporte da Loritta.

Ticket Bot Um bot de suporte feito usando threads para o Discord, 100% customizável, feito em JavaScript e inspirado no Rio Helper do servidor Elixir

ADG 6 Dec 21, 2022
A JavaScript Library for things I use often, as well as some helper functions

Elements A JavaScript Library for things I use often, as well as some helper functions. Full documentation below. Inspired by Habitat, another library

Magnogen 3 Apr 21, 2022
A set of useful helper methods for writing functions to handle Cloudflare Pub/Sub messages (https://developers.cloudflare.com/pub-sub/)

pubsub A set of useful helper methods for writing functions to handle Cloudflare Pub/Sub messages. This includes: A isValidBrokerRequest helper for au

Cloudflare 18 Dec 4, 2022
Cloud Native, DevOps, GitOps, Open Source, industry news, culture, and the 'ish between.

DevOps'ish DevOps'ish is authored by Chris Short and Made in Michigan. What is DevOps? I'm glad you asked. Newsletter Writing Process Everyone needs a

Chris Short 7 Jan 12, 2022
Functions Recipes is a library of examples to help you getting started with Salesforce Functions and get used to their main features.

Functions Recipes Introduction Salesforce Functions lets you use the Salesforce Platform for building event-driven, elastically scalable apps and expe

Trailhead Apps 172 Dec 29, 2022
Next-level academia! Repository for the Native Overleaf project, attempting to integrate Overleaf with native OS features for macOS, Linux and Windows.

Native Overleaf Overleaf is a fantastic webtool for writing and cooperating on LaTeX documents. However, would it not be even better if it were to beh

Floris-Jan Willemsen 40 Dec 18, 2022
This is a jquery ui sortable helper plugin for handy tree type structure sotable.

Tree Sortable A drag and drop list item sorting and level changing library. Motivation The jQuery-ui's sortable plugin allows us to sort items vertica

Sajeeb Ahamed 10 Dec 23, 2022
An npm package for demonstration purposes using TypeScript to build for both the ECMAScript Module format (i.e. ESM or ES Module) and CommonJS Module format. It can be used in Node.js and browser applications.

An npm package for demonstration purposes using TypeScript to build for both the ECMAScript Module format (i.e. ESM or ES Module) and CommonJS Module format. It can be used in Node.js and browser applications.

Snyk Labs 57 Dec 28, 2022
Universal importer for CommonJS and ESM in Node.js

ModuleImporter by Nicholas C. Zakas If you find this useful, please consider supporting my work with a donation. Description A utility for seamlessly

Human Who Codes 18 Dec 2, 2022
Node.js ESM loader for chaining multiple custom loaders.

ESMultiloader Node.js ESM loader for chaining multiple custom loaders. Fast and lightweight No configuration required, but configurable if needed Usag

jhmaster2000 2 Sep 12, 2022
Node.js loader for compiling ESM & TypeScript modules to CommonJS

cjs-loader Node.js require() hook to instantaneously transform ESM & TypeScript to CommonJS on demand using esbuild. Features Transforms ESM & TypeScr

esbuild kit 40 Dec 13, 2022
Node.js loader for compiling TypeScript modules to ESM

esm-loader Node.js import hook to instantaneously transform TypeScript to ESM on demand using esbuild. Features Transforms TypeScript to ESM on demand

esbuild kit 90 Jan 4, 2023
Minimal utility to convert to or from any timezone. Deno/Node/Browser. ESM/CommonJS.

minitz Features Convert dates between any timezone supported by the system. Parses ISO8601 time strings. MIT licensed, use the library any way you wan

Hexagon 14 Oct 10, 2022
⏱ Simple Alpine.js plugin to display the human-readable distance between a date and now.

⏱ Alpine TimeAgo ⏱ An Alpine.js plugin to return the distance between a given date and now in words (like "3 months ago", "about 2 hours ago" or "in a

Marc Reichel 47 Dec 22, 2022
🍭 search-buddy ultra lightweight javascript plugin that can help you create instant search and/or facilitate navigation between pages.

?? search-buddy search-buddy is an open‑source ultra lightweight javascript plugin (* <1kb). It can help you create instant search and/or facilitate n

Michael 4 Jun 16, 2022
A plugin that can find the paths between two notes. Not sure who will want to use it...

Obsidian Path Finder Plugin Install BRAT Install Obsidian42-BRAT plugin. Click Add new beta plugin and fill in jerrywcy/obsidian-path-finder. Activate

jerrywcy 29 Dec 31, 2022