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 Oct 11, 2021
1 parent a574665 commit 38865d1
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 22 deletions.
38 changes: 17 additions & 21 deletions packages/babel-helpers/scripts/generate-helpers.js
Expand Up @@ -8,21 +8,25 @@ 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")) {
console.error("ignoring", filePath);
Expand Down Expand Up @@ -79,24 +83,16 @@ import template from "@babel/template";
);
});

const intro = isValidId
? "export "
: `export { ${varName} as ${helperName} }\n`;
const [helperName] = file.split(".");

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 38865d1

Please sign in to comment.