Zach’s ugly mug (his face)

Zach Leatherman

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

June 14, 2022 #11 Popular

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’s ugly mug (his face)

Zach is a builder for the web with IndieWeb Avatar for https://www.netlify.comNetlify. He created the IndieWeb Avatar for https://www.11ty.devEleventy site generator and is still fixated on web fonts. His public speaking résumé includes talks in eight different countries at events like Jamstack Conf, Beyond Tellerrand, Smashing Conference, CSSConf, and The White House. He is an emeritus of Filament Group, NEJS CONF, and still helps out with nebraskajs’s AvatarNebraskaJS. Read more about Zach »

Previous
Dear Paul
Next
The many definitions of Server-Side Rendering

1 Retweet

ESnextNews

Shamelessly plug your related post:

Sharing on social media?

This is what will show up when you share this post on Social Media:

How did you do this? I automated my Open Graph images. (Peer behind the curtain at the test page)