Skip to content

Instantly share code, notes, and snippets.

@lamhungypl
Last active January 11, 2022 02:58
Show Gist options
  • Save lamhungypl/17080c26a60d5ddd94d82e82648c6b36 to your computer and use it in GitHub Desktop.
Save lamhungypl/17080c26a60d5ddd94d82e82648c6b36 to your computer and use it in GitHub Desktop.
New component react cli
// 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",
},
  
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment