Skip to content

Commit

Permalink
export only default object from helpers-generated.ts
Browse files Browse the repository at this point in the history
This obviates the need to carefully handle helper names that cannot be
directly used as identifiers, and also very slightly reduces the amount
of boilerplate that ends up in babel-standalone.
  • Loading branch information
lightmare committed Nov 5, 2021
1 parent a6a5269 commit 1381ae2
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 21 deletions.
36 changes: 16 additions & 20 deletions packages/babel-helpers/scripts/generate-helpers.js
Expand Up @@ -8,20 +8,26 @@ const IGNORED_FILES = new Set(["package.json"]);
export default async function generateHelpers() {
let output = `/*
* This file is auto-generated! Do not modify it directly.
* To re-generate run 'make build'
* To re-generate run 'yarn gulp generate-runtime-helpers'
*/
import template from "@babel/template";
function helper(minVersion, source) {
return Object.freeze({
minVersion,
ast: () => template.program.ast(source),
})
}
export default Object.freeze({
`;

for (const file of (await fs.promises.readdir(HELPERS_FOLDER)).sort()) {
if (IGNORED_FILES.has(file)) continue;
if (file.startsWith(".")) continue; // ignore e.g. vim swap files

const [helperName] = file.split(".");
const isValidId = isValidBindingIdentifier(helperName);
const varName = isValidId ? helperName : `_${helperName}`;

const filePath = join(fileURLToPath(HELPERS_FOLDER), file);
if (!file.endsWith(".js")) {
Expand All @@ -45,24 +51,14 @@ import template from "@babel/template";
// Remove multiple newlines
.replace(/\n{2,}/g, "\n");

const intro = isValidId
? "export "
: `export { ${varName} as ${helperName} }\n`;

output += `\n${intro}const ${varName} = {
minVersion: ${JSON.stringify(minVersion)},
ast: () => template.program.ast(${JSON.stringify(source)})
};\n`;
output += `\
${JSON.stringify(helperName)}: helper(
${JSON.stringify(minVersion)},
${JSON.stringify(source)},
),
`;
}

output += "});";
return output;
}

function isValidBindingIdentifier(name) {
try {
Function(`var ${name}`);
return true;
} catch {
return false;
}
}
2 changes: 1 addition & 1 deletion packages/babel-helpers/src/helpers.ts
@@ -1,7 +1,7 @@
import template from "@babel/template";
import type * as t from "@babel/types";

import * as generated from "./helpers-generated";
import generated from "./helpers-generated";

interface Helper {
minVersion: string;
Expand Down

0 comments on commit 1381ae2

Please sign in to comment.