Skip to content

Instantly share code, notes, and snippets.

@vjwilson
Created October 15, 2017 17:58
Show Gist options
  • Save vjwilson/18d38e9c8aff199026d709ed01e4fa4c to your computer and use it in GitHub Desktop.
Save vjwilson/18d38e9c8aff199026d709ed01e4fa4c to your computer and use it in GitHub Desktop.
node script to copy create a component folder, with component, test, SASS, and doc files)
/*
* @usage
* 1.) create a folder with skeletons files for the file you want for you component
* 2.) put the following line in the npm scripts section of your package.json
* "generate:component": "babel-node helpers/componentGenerator.js"
* 3.) To generate a component, run the script with the new component name as argument
* e.g.,
* npm run generate:component seating-chart
*
* will start a new component at
* app/src/components/seating-chart/SeatingChart.jsx
*/
import chalk from 'chalk';
import fs from 'fs';
function getTitleCase(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
console.log(chalk.blue('Generating new component. This will take a moment...'));
const newHyphenatedName = process.argv[2];
if (!newHyphenatedName) {
console.error(chalk.red('No component name given.'));
process.exit(1);
}
const newComponentName = newHyphenatedName
.split('-')
.map(segment => getTitleCase(segment))
.join('');
console.log(chalk.green(`New component name is: ${newComponentName}`));
try {
process.chdir('app/src/components');
console.log(chalk.blue(`Changed to directory: ${process.cwd()}`));
} catch (err) {
console.error(chalk.red(`chdir: ${err}`));
process.exit(1);
}
console.log(chalk.green(`Making directory: ${newHyphenatedName}...`));
fs.mkdirSync(newHyphenatedName);
const newFiles = [
'_component.jsx',
'_component.doc.jsx',
'_component.scss',
'_component.spec.jsx',
];
newFiles.forEach((filename) => {
try {
const data = fs.readFileSync(`_component-template/${filename}`, 'utf8');
const result = data
.replace(/Foo/g, newComponentName)
.replace(/foo/g, newHyphenatedName);
const newFilename = filename.replace(/_component/g, newComponentName);
console.log(chalk.green(`Generating file: ${newFilename}...`));
fs.writeFileSync(`${newHyphenatedName}/${newFilename}`, result, 'utf8');
} catch (err) {
console.error(err);
process.exit(1);
}
});
console.log(chalk.green('Finished generating new component.'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment