// component-template.js
const toPascalCase = (str) =>
str
.split(/\W/)
.map((s) =>
s.replace(
/\w\S*/g,
(m) => `${m.charAt(0).toUpperCase()}${m.substring(1).toLowerCase()}`,
),
)
.join('');
// component.tsx
const component = (name) => `
import React from 'react';
export interface ${name}Props {
}
const ${name} = (props: ${name}Props) => {
return (
<div>
${name}
</div>
)
}
export default ${name};
`;
// index.tsx
const barrel = (name) => `export { default } from './${name}';`;
module.exports = {
toPascalCase,
component,
barrel,
};
// index.js
const fs = require('fs');
const { component, toPascalCase, barrel } = require('./component-template.js');
// grab component name from terminal argument
if (!name) throw new Error('Require component name.');
const [name] = process.argv.slice(2);
const componentName = toPascalCase(name);
const dir = `${process.env.INIT_CWD}/${componentName}`;
// throw an error if the file already exists
if (fs.existsSync(dir)) throw new Error('component already existed.');
// create the folder
fs.mkdirSync(dir);
console.log(`New component in ${dir}`);
function writeFileErrorHandler(err) {
if (err) throw err;
}
// component.tsx
fs.writeFile(
`${dir}/${componentName}.tsx`,
component(componentName),
writeFileErrorHandler,
);
// index.tsx
fs.writeFile(`${dir}/index.tsx`, barrel(componentName), writeFileErrorHandler);
//package.json
"scripts": {
"new-component": "node .cli/new-component",
},