Zach’s ugly mug (his face) Zach Leat­herman

Use esm-import-transformer for “isomorphic-ish” ECMAScript Modules

June 14, 2022
esm-import-transformer

Perform transformations on ESM import syntax (using import maps or to a dynamic import).

0%
Popularity
npm5m Monthly downloads sparkline for esm-import-transformer, ranging 178k to 576k cdn3k Monthly jsDelivr CDN hits sparkline for esm-import-transformer, ranging 10 to 1k
Versions
Monthly publishes sparkline for esm-import-transformer, ranging 0 to 2 9 versions in
3.0.5
Audit
0 reports
1 dep
Issues
0
PRs
0
1

This is a small Node utility that uses Acorn to change the location of import specifier locations.

// Before
import {html, css, LitElement} from "lit";

// After
import {html, css, LitElement} from "https://cdn.jsdelivr.net/gh/lit/dist@2/core/lit-core.min.js";

This is useful when you want to use the same input source JavaScript code to run in both a server context and a client context, without making huge modifications to the code! It could also be used as a build-time workaround for import maps until browser support improves.

Practically speaking, I used this in a couple places to implement the SSR examples for <is-land>.

The transformations are mapped using standard import maps objects and the package can run as an ES module (via import) or in CommonJS (via require).

Usage

Pass in a source code string and an import maps object.

// Import the ES Module:
import { ImportTransformer } from "esm-import-transformer";

// or use with CommonJS:
// const { ImportTransformer } = require("esm-import-transformer");

let it = new ImportTransformer();

let sourceCode = `import {html, css, LitElement} from "lit";`;

let importMap = {
  imports: {
    lit: "https://cdn.jsdelivr.net/gh/lit/dist@2/core/lit-core.min.js"
  }
};

let outputCode = it.transform(sourceCode, importMap);

Installation

Available on npm and GitHub

npm install esm-import-transformer

Zach Leatherman is a builder for the web at Font Awesome and the creator of Build Awesome (née Eleventy/11ty), an award-winning open source website generator. He measures website performance with speedlify and at one point became too fixated on web fonts. He has given 86 talks in nine different countries at events like Beyond Tellerrand, Smashing Conference, Jamstack Conf, CSSConf, and The White House. Learn more about Zach »