Skip to content

Commit 5dc5176

Browse files
authored
(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
1 parent 15ed6a4 commit 5dc5176

File tree

1 file changed

+10
-26
lines changed

1 file changed

+10
-26
lines changed

tools/build_node.js

Lines changed: 10 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -8,25 +8,13 @@ const { filter } = require("./lib/dependencies");
88
const { rollupWrite } = require("./lib/bundling.js");
99
const log = (...args) => console.log(...args);
1010

11-
const safeImportName = (s) => {
12-
s = s.replace(/-/g, "_");
13-
if (/^\d/.test(s)) s = `L_${s}`;
14-
return s;
15-
};
16-
17-
async function buildESMIndex(name, languages) {
18-
const header = `import hljs from './core.js';`;
19-
const footer = "export default hljs;";
20-
21-
22-
const registration = languages.map((lang) => {
23-
const importName = safeImportName(lang.name);
24-
return `import ${importName} from './languages/${lang.name}.js';\n` +
25-
`hljs.registerLanguage('${lang.name}', ${importName});`;
26-
});
27-
28-
const index = `${header}\n\n${registration.join("\n")}\n\n${footer}`;
29-
await fs.writeFile(`${process.env.BUILD_DIR}/es/${name}.js`, index);
11+
// https://nodejs.org/api/packages.html#packages_writing_dual_packages_while_avoiding_or_minimizing_hazards
12+
async function buildESMStub(name) {
13+
const code =
14+
`// https://nodejs.org/api/packages.html#packages_writing_dual_packages_while_avoiding_or_minimizing_hazards\n` +
15+
`import hljs from '../lib/${name}.js';\n` +
16+
`export default hljs;\n`;
17+
await fs.writeFile(`${process.env.BUILD_DIR}/es/${name}.js`, code);
3018
}
3119

3220
async function buildCJSIndex(name, languages) {
@@ -97,11 +85,7 @@ async function buildNodeHighlightJS(options) {
9785
const output = { ...config.rollup.node.output, file: `${process.env.BUILD_DIR}/lib/core.js` };
9886
await rollupWrite(input, output);
9987
if (options.esm) {
100-
await rollupWrite(input, {
101-
...output,
102-
format: "es",
103-
file: `${process.env.BUILD_DIR}/es/core.js`
104-
});
88+
buildESMStub("core");
10589
}
10690
}
10791

@@ -191,8 +175,8 @@ async function buildNode(options) {
191175

192176
if (options.esm) {
193177
await fs.writeFile(`${process.env.BUILD_DIR}/es/package.json`, `{ "type": "module" }`);
194-
await buildESMIndex("index", languages);
195-
await buildESMIndex("common", common);
178+
await buildESMStub("index");
179+
await buildESMStub("common");
196180
await buildESMUtils();
197181
}
198182
await buildCJSIndex("index", languages);

0 commit comments

Comments
 (0)