From 5dc5176c5c1728ce950fba75a40f55881b689f83 Mon Sep 17 00:00:00 2001 From: Josh Goebel Date: Sat, 29 May 2021 20:44:50 -0400 Subject: [PATCH] (chore) dual package (#3188) Avoid dual package hazard by making our ES6 modules simply require our CJS modules. (for HLJS core, so that someone pulling in the library by both ES and CJS will not have two different instances) Per https://nodejs.org/api/packages.html#packages_writing_dual_packages_while_avoiding_or_minimizing_hazards --- tools/build_node.js | 36 ++++++++++-------------------------- 1 file changed, 10 insertions(+), 26 deletions(-) diff --git a/tools/build_node.js b/tools/build_node.js index eca391d60f..5d6bb6e7d8 100644 --- a/tools/build_node.js +++ b/tools/build_node.js @@ -8,25 +8,13 @@ const { filter } = require("./lib/dependencies"); const { rollupWrite } = require("./lib/bundling.js"); const log = (...args) => console.log(...args); -const safeImportName = (s) => { - s = s.replace(/-/g, "_"); - if (/^\d/.test(s)) s = `L_${s}`; - return s; -}; - -async function buildESMIndex(name, languages) { - const header = `import hljs from './core.js';`; - const footer = "export default hljs;"; - - - const registration = languages.map((lang) => { - const importName = safeImportName(lang.name); - return `import ${importName} from './languages/${lang.name}.js';\n` + - `hljs.registerLanguage('${lang.name}', ${importName});`; - }); - - const index = `${header}\n\n${registration.join("\n")}\n\n${footer}`; - await fs.writeFile(`${process.env.BUILD_DIR}/es/${name}.js`, index); +// https://nodejs.org/api/packages.html#packages_writing_dual_packages_while_avoiding_or_minimizing_hazards +async function buildESMStub(name) { + const code = + `// https://nodejs.org/api/packages.html#packages_writing_dual_packages_while_avoiding_or_minimizing_hazards\n` + + `import hljs from '../lib/${name}.js';\n` + + `export default hljs;\n`; + await fs.writeFile(`${process.env.BUILD_DIR}/es/${name}.js`, code); } async function buildCJSIndex(name, languages) { @@ -97,11 +85,7 @@ async function buildNodeHighlightJS(options) { const output = { ...config.rollup.node.output, file: `${process.env.BUILD_DIR}/lib/core.js` }; await rollupWrite(input, output); if (options.esm) { - await rollupWrite(input, { - ...output, - format: "es", - file: `${process.env.BUILD_DIR}/es/core.js` - }); + buildESMStub("core"); } } @@ -191,8 +175,8 @@ async function buildNode(options) { if (options.esm) { await fs.writeFile(`${process.env.BUILD_DIR}/es/package.json`, `{ "type": "module" }`); - await buildESMIndex("index", languages); - await buildESMIndex("common", common); + await buildESMStub("index"); + await buildESMStub("common"); await buildESMUtils(); } await buildCJSIndex("index", languages);