Giter Site home page Giter Site logo

esm-cjs-shim's Introduction

esm-cjs-shim

Note: only needed if node's static analysis fails: https://nodejs.org/dist/latest/docs/api/esm.html#esm_interoperability_with_commonjs

Problem: importing CJS modules from ESM in node means you get the exports object as your default export, so you can't do named imports.

Solution: write a --loader that shims CJS modules loaded from ESM so they have named exports.

When the ESM loader resolves something to be CommonJS, rewrite the resolution to an ESM shim.

ESM shim does 2x things:

export * from 'esm-shim://export/<encoded payload>';
import 'esm-shim://discover-exports/<encoded payload>';
// //discover-exports/
import cjs from 'commonjs-module';
const allExports = Buffer.from(JSON.stringify(Object.keys(cjs)).toString('base64');
await import(`esm-shim://report-exports/<unique ID>/${ allExports }`);
// //export/
import cjs from 'commonjs-module';
const {foo, bar, baz} = cjs;
export {foo, bar, baz};

For every CJS imported from ESM, there are 3x "virtual" modules created:

  • esm-shim://export/
  • esm-shim://discover-exports/
  • esm-shim://report-exports/

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.