Skip to content

Instantly share code, notes, and snippets.

@mohdovais
Last active February 10, 2023 21:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohdovais/cad603d3350d412d0b3cce67f7793378 to your computer and use it in GitHub Desktop.
Save mohdovais/cad603d3350d412d0b3cce67f7793378 to your computer and use it in GitHub Desktop.
Rollup.js plugin to import UMD modules. It exports umd function expression as default in esm
import { normalize } from "path";
import { readFileSync } from "fs";
import { isRegExp } from "util";
import { parse } from "acorn";
const toArray = item => Array.isArray(item) ? item : [item];
// https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript#answer-3561711
const escapeRegexpStr = str => str.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
export default function importUMD(modules, config) {
const _config = Object.assign({ ecmaVersion: 2020 }, config);
const _modules = toArray(modules).map((item) =>
isRegExp(item) ? item : new RegExp(escapeRegexpStr(normalize(item)), "i")
);
return {
name: "import-umd",
load(id) {
if (_modules.some((module) => module.test(id))) {
const content = readFileSync(id, "utf8");
const ast = parse(content, _config);
const { start, end } = ast.body[0].expression.arguments[0];
return `export default ${content.substring(start, end)}`;
}
return null;
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment