Node.js loader for compiling ESM & TypeScript modules to CommonJS

Overview

cjs-loader

Node.js require() hook to instantaneously transform ESM & TypeScript to CommonJS on demand using esbuild.

Features

  • Transforms ESM & TypeScript to CommonJS on demand
  • Supports TS extensions .cjs & .mjs (.cts & .mts)
  • Cached for performance boost
  • Supports Node.js v12.16.2+
  • Handles node: import prefixes

Tip:

cjs-loader doesn't hook into dynamic import() calls.

Use this with esm-loader for import() support. Alternatively, use tsx to handle them both automatically.

Install

npm install --save-dev @esbuild-kit/cjs-loader

Usage

Pass @esbuild/cjs-loader into the --require flag

node -r @esbuild/cjs-loader ./file.js

TypeScript configuration

The following properties are used from tsconfig.json in the working directory:

  • jsxFactory
  • jsxFragmentFactory

Cache

Modules transformations are cached in the system cache directory (TMPDIR). Transforms are cached by content hash so duplicate dependencies are not re-transformed.

Set environment variable ESBK_DISABLE_CACHE to a truthy value to disable the cache:

ESBK_DISABLE_CACHE=1 node -r @esbuild/cjs-loader ./file.js

Related

Comments
  • Only transform files that need to be transformed

    Only transform files that need to be transformed

    This fixes a ton of weird bugs we are having, such as __name not defined in our webpack bundle, and made our code run much faster, while still working with ESM modules.

    opened by dylang 15
  • Work with ts-node instead of causing a TypeError

    Work with ts-node instead of causing a TypeError

    Prevents the following error thrown when projects like ts-node also try to register .mjs.

    TypeError: Cannot assign to read only property '.mjs' of object '[object Object]' w

    This can happen in dependencies like cosmic-config that use ts-node because they don't know that tsx is already loaded.

    opened by dylang 9
  • feature request: export an unregister method for returning to Node's require methods

    feature request: export an unregister method for returning to Node's require methods

    In my Jest config I have import '@esbuild-kit/cjs-loader'; so that the config can load node modules that use ESM.

    However, because we don't have a way to unregister the loader, it continues to be used through all of the tests, slowing down Jest and double-compiling those that we want transformed.

    Ideally, it would be something like:

    import { unregisterLoader } from '@esbuild-kit/cjs-loader';
    import { } from 'esm module 1';
    import { } from 'esm module 2';
    
    unregisterLoader();
    
    // rest of Jest config.
    
    opened by dylang 3
  • cssom parser failing when using @esbuild-kit/cjs-loader

    cssom parser failing when using @esbuild-kit/cjs-loader

    I've ran into a problem using tsx and managed to isolate the problem as an issue with @esbuild-kit/cjs-loader and cssom. When using the loader, the cssom parser fails, but not when using e.g. esbuild-register or no loader. I've reproduced the problem and included the necessary files in this issue. However, I'm not knowledgeable enough to know where to look next, so it would be great if I can get some help.

    bug 
    opened by steabert 2
  • resolve js -> ts also for path alias

    resolve js -> ts also for path alias

    I noticed that tsx correctly resolves to .ts files when the import ends with .js. But it does not work if the file is behind a TypeScript path alias.

    This demonstrates the problem: https://stackblitz.com/edit/node-uvmbub?file=index.ts

    The proposed change works well in my project. If you agree, I can also make a corresponding PR for esm-loader

    opened by schummar 2
  • feat: custom tsconfig path via `ESBK_TSCONFIG_PATH`

    feat: custom tsconfig path via `ESBK_TSCONFIG_PATH`

    Summary

    This PR adds support for ESBK_TSCONFIG_NAME=tsconfig.custom.json and passes it down to get-tsconfig.

    (This will be used for the upcoming tsx --tsconfig arg)

    released 
    opened by amitdahan 2
  • refactor: defer loaders for cjs, cts, mts to js

    refactor: defer loaders for cjs, cts, mts to js

    No behavioral change.

    Minor refactor to remove explicitly registering loaders for .cjs, .cts, and .mts because Node.js' CJS loader actually just fallsback unrecognized extensions to the .js loader.

    That said, transformations are still applied.

    released 
    opened by privatenumber 1
  • feat: dynamic import to interop with modules using __esModule

    feat: dynamic import to interop with modules using __esModule

    Problem

    Dynamically importing an ESM .js file resulting in getting wrapped in {"default": ... }.

    Importing the following would look like this:

    export default 1234
    
    {"default":{"default":1234}}
    

    Changes

    • New core-utils transforms dynamic imports to interop with transformed modules. Although this is a feature, it's also a breaking change.
    released 
    opened by privatenumber 1
  • Custom ESM karma server breaks with tsx

    Custom ESM karma server breaks with tsx

    Bug description

    I have a project that runs a custom Karma server. It is custom because I want to use ESM for Karma while it supports only CJS by default. However, if I try to run it with tsx (command is tsx karma.config.ts), the server fails with the following error:

    07 11 2022 16:25:58.760:ERROR [karma-server]: Server start failed on port 9876: Error: No provider for "proxies"! (Resolving: webServer -> proxies)
    <root>\node_modules\di\lib\injector.js:22
        return new Error(stack ? msg + ' (Resolving: ' + stack + ')' : msg);
               ^
    
    Error: No provider for "proxies"! (Resolving: webServer -> proxies)
        at error (<root>\node_modules\di\lib\injector.js:22:12)
        at Object.get (<root>\node_modules\di\lib\injector.js:9:13)
        at get (<root>\node_modules\di\lib\injector.js:54:19)
        at <anonymous> (<root>\node_modules\di\lib\injector.js:71:14)
        at Array.map (<anonymous>)
        at Object.invoke (<root>\node_modules\di\lib\injector.js:70:31)
        at createWebServer (<root>\node_modules\karma\lib\web-server.js:65:44)
        at Array.invoke (<root>\node_modules\di\lib\injector.js:75:15)
        at Object.get (<root>\node_modules\di\lib\injector.js:48:41)
        at Server._close (<root>\node_modules\karma\lib\server.js:438:38)
    

    However, it works correctly if I use node --loader @esbuild-kit/esm-loader karma.config.ts instead, it works as expected.

    Also, I noticed that if I use two loaders (for ESM and CJS) at the same time (command node --loader @esbuild-kit/esm-loader -r @esbuild-kit/cjs-loader karma.config.ts), it also fails with the same error.

    Reproduction

    1. Clone this repo.
    2. npm install
    3. npm run test

    Environment

      System:
        OS: Windows 10 10.0.22000
        CPU: (12) x64 12th Gen Intel(R) Core(TM) i7-1255U
        Memory: 22.32 GB / 47.71 GB
      Binaries:
        Node: 19.0.0 - C:\Program Files\nodejs\node.EXE
        Yarn: 1.22.19 - C:\Program Files\nodejs\yarn.CMD
        npm: 8.19.2 - C:\Program Files\nodejs\npm.CMD
      npmPackages:
        tsx: ^3.11.0 => 3.11.0
    

    Can you contribute a fix?

    • [ ] I’m interested in opening a pull request for this issue.
    bug 
    opened by Lodin 1
Releases(v2.4.1)
Owner
esbuild kit
High quality tools enhanced by esbuild
esbuild kit
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
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
Babel plugin and helper functions for interoperation between Node.js native ESM and Babel ESM

babel-plugin-node-cjs-interop and node-cjs-interop: fix the default import interoperability issue in Node.js The problem to solve Consider the followi

Masaki Hara 15 Nov 6, 2022
📦 🍣 Zero-config JS bundler for ESM, CommonJS, and .d.ts outputs

pkgroll Write your code in ESM & TypeScript and bundle it to get ESM, CommonJS, and type declaration outputs with a single command! Features Zero conf

hiroki osame 153 Dec 23, 2022
Recursively publish ESM packages as CommonJS!

Commonify.js For us who are still relying on CommonJS, or using Electron which does not support ESM. ?? See also build-electron I made this tool that

Mikael Finstad 31 Dec 29, 2022
📦 🍣 Zero-config JS bundler for ESM, CommonJS, and .d.ts outputs. (Forked from pkgroll)

?? ?? puild (A fork of pkgroll) Write your code in ESM & TypeScript and bundle it to get ESM, CommonJS, and type declaration outputs with a single com

ʀᴀʏ 6 Sep 6, 2022
utility library for promise, support both commonjs and ESM

promising-utils A utility library for promise, supports both commonjs and ESM npm install promising-utils --save yarn add promising-utils wait Used wh

Qiang Li 4 Oct 18, 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
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
Command-line toolkit for parsing, compiling, transpiling, optimizing, linking, dataizing, and running EOLANG programs

First, you install npm and Java SE. Then, you install eolang package: $ npm install eolang Then, you write a simple EO program in hello.eo file in th

objectionary 17 Nov 17, 2022
CLI utility that parses argv, loads your specified file, and passes the parsed argv into your file's exported function. Supports ESM/TypeScript/etc out of the box.

cleffa CLI tool that: Parses argv into an object (of command-line flags) and an array of positional arguments Loads a function from the specified file

Lily Scott 9 Mar 6, 2022
This project is based on the Awesome Books app repo, refactored with ES6 and organized with modules. The purpose of this project is to learn functionality organization using JavaScript modules.

Awesome Books with ES6 and modules A basic app project built with HTML, CSS and JS ES6 to keep track of awesome books. Built With HTML/CSS and JS best

Karla Delgado 10 Aug 27, 2022
testing rollup dist for cjs/esm

std.module.format version 0.1.3 std.module.format Overview TLDR Avoid Default Exports and Prefer Named Exports Context Summary Decision ECMAScript Mod

sam bacha 5 Dec 11, 2022
Three.js boilerplate project configured with typescript, webpack and css/style loader, HTTPS local server, and a sample test codes !!

three.js-boilerplate Welcome, this is a three.js boilerplate project where you can clone it and start to work !!! Installed and Configured Items: Type

pravin poudel 4 Jul 6, 2022
Cumcord loader on Browser (Chrome, Firefox, etc)

CumLoad CumLoad is a Chrome Extension that allows you to load Cumcord and plugins inside your Discord pages. We recommend using the MV2 version becaus

Cumcord Loader Plugins 11 Nov 7, 2022
The Termpura loader core package.

This project is a Work in Progress and currently in development. The API is subject to change without warning. Install npm install @termpura/core Usag

Termpura 2 Oct 15, 2022