Zach’s ugly mug (his face) Zach Leatherman

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

June 14, 2022

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

< Newer
Dear Paul
Older >
The many definitions of Server-Side Rendering

Zach Leatherman IndieWeb Avatar for https://zachleat.com/is a builder for the web at IndieWeb Avatar for https://fontawesome.com/Font Awesome and the creator/maintainer of IndieWeb Avatar for https://www.11ty.devEleventy (11ty), an award-winning open source site generator. At one point he became entirely too fixated on web fonts. He has given 84 talks in nine different countries at events like Beyond Tellerrand, Smashing Conference, Jamstack Conf, CSSConf, and The White House. Formerly part of CloudCannon, Netlify, Filament Group, NEJS CONF, and NebraskaJS. Learn more about Zach »

2 Reposts

ESnextNewsIndieWeb Avatar for https://www.reddit.com

8 Likes

aaron hansMatt BiilmannMatt Rossman 🍌Patrick HaugLeonardo MatosPhil HawksworthBrett Jankord Jason Gorman
Shamelessly plug your related post

These are webmentions via the IndieWeb and webmention.io.

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)