Last active
February 10, 2023 21:28
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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