Files

56 lines
1.7 KiB
TypeScript
Raw Permalink Normal View History

2024-04-29 11:34:10 +02:00
import * as path from 'node:path';
2025-09-30 21:19:45 +10:00
import { watch } from 'node:fs';
2024-04-29 11:34:10 +02:00
import { readFile, writeFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
2025-09-11 16:35:13 +05:30
import { globby } from 'globby';
2024-04-29 11:34:10 +02:00
import { minify } from 'terser';
const currentDirectory = fileURLToPath(new URL('.', import.meta.url));
const preamble = [
'// This file is autogenerated. Do not edit it directly.',
'// To update it, modify the corresponding source file and run `pnpm inline-scripts`.',
].join('\n');
2025-09-30 21:19:45 +10:00
async function buildFile(sourceFile: string) {
const sourceContent = await readFile(sourceFile, 'utf8');
const { code: minifiedCode } = await minify(sourceContent, { ecma: 2020 });
const escapedCode = minifiedCode!.replace(/'/g, "\\'");
const output = [
preamble,
'',
'// prettier-ignore',
`export const script = '${escapedCode}';\n`,
].join('\n');
const outputFilename = sourceFile.replace('.template.js', '.min.ts');
await writeFile(outputFilename, output);
}
2024-04-29 11:34:10 +02:00
/**
2024-11-21 10:18:21 +01:00
* Finds files with the `.template.js` extension in the `react` package, minifies them, and writes
2024-04-29 11:34:10 +02:00
* the code to a new file with the `.min.ts` extension.
* The minified code is then exported as a string literal.
*/
async function run() {
2025-09-11 16:35:13 +05:30
const files = await globby('**/*.template.js', {
2024-04-29 11:34:10 +02:00
absolute: true,
2024-11-21 10:18:21 +01:00
cwd: path.resolve(currentDirectory, '../packages/react/src'),
2024-04-29 11:34:10 +02:00
});
2025-09-30 21:19:45 +10:00
await Promise.all(files.map(buildFile));
return files;
2024-04-29 11:34:10 +02:00
}
2025-09-30 21:19:45 +10:00
const files = await run();
if (process.argv.includes('--watch') || process.argv.includes('-w')) {
// eslint-disable-next-line no-console
console.log('Processing *.template.js files in watch mode...');
files.forEach((file) => {
watch(file, (eventType) => {
if (eventType === 'change') {
buildFile(file);
}
});
});
}