Skip to content
jshacks.dev
Tooling

Scaffold files with a small generator script

Scaffold new files from templates with a short Node.js script that takes a name argument, writes the files and refuses to overwrite existing ones.

2 min read
Summarize in AI

A template folder and fifty lines of script often beat a generator framework.

scripts/new-component.mjsJavaScript
import { mkdir, writeFile } from 'node:fs/promises';
import { join } from 'node:path';

const name = process.argv[2];
if (!name || !/^[A-Z][A-Za-z0-9]*$/.test(name)) {
  console.error('Usage: node scripts/new-component.mjs PascalCaseName');
  process.exit(1);
}

const dir = join('src', 'components', name);
await mkdir(dir, { recursive: true });

const files = {
  [`${name}.js`]: `export function ${name}() {\n  return '${name}';\n}\n`,
  [`${name}.test.js`]: `import { test } from 'node:test';\nimport assert from 'node:assert/strict';\nimport { ${name} } from './${name}.js';\n\ntest('${name}', () => {\n  assert.equal(${name}(), '${name}');\n});\n`,
};

for (const [file, body] of Object.entries(files)) {
  await writeFile(join(dir, file), body, { flag: 'wx' });
}
console.log(`created ${dir}`);
Shell
node scripts/new-component.mjs Button
Text
created src/components/Button

The wx flag makes writeFile fail with EEXIST if the file is already there, so the script cannot overwrite your work. The name check keeps a typo from creating a folder with a strange name. See [the fs.writeFile flags](https://nodejs.org/docs/latest-v24.x/api/fs.html#file-system-flags).

Once you need prompts, conditionals and many templates, a library such as Plop pays for itself. Until then, a script you can read in one screen is easier to change than a framework you have to learn first, and it lives next to the code it generates.

Also inFunctions
Share

More snippets

Tooling

Create a Vite project from a template

Create a Vite project from a template with npm create vite, choose the vanilla-ts or react-ts template and see which files it generates.

1 min read
Functions

Write a once function

Write a once function in JavaScript that runs a callback a single time and returns the cached result after that. Works in any Node.js, ES2015 or later.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.