In a recent project we settled on how we decided to have our React components live in their own folders, so I aimed to write a quick script that could easily create the structure and files, and even create a throwaway Jest test that passed.
Here's what I came up with, feel free to take and modify for your own needs.
#!/bin/sh
โ
green='\033[0;32m'
magenta='\033[0;35m'
โ
alias Reset="tput sgr0"
โ
cecho() {
echo "${2}${1}"
Reset # Reset to normal.
return
}
โ
CONTINUE=false
โ
cecho "What do you want to name your component?" $green
read component
echo ""
cecho "What directory should $component live? (relative to src/)" $green
read directory
echo ""
โ
mkdir -p src/$directory/$component
cd src/$directory/$component
โ
# Make PasCal case dasherized for sass
dasherizedcomponent=$(echo $component \
| sed 's/\(.\)\([A-Z]\)/\1-\2/g' \
| tr '[:upper:]' '[:lower:]')
โ
echo "@import '/styles/scss/variables';
// Make $component Excellent!
.$dasherizedcomponent {
// Block thing for .$dasherizedcomponent
&-element {
// Element things for .$dasherizedcomponent
}
}" >> ${component}.scss;
โ
echo "import React, { useState } from 'react';
import './$component.scss';
โ
const $component = ({text}) => {
const [count, setCount] = useState(0);
โ
return (
<div className='$dasherizedcomponent'>
{text}
</div>
)
}
โ
export default $component;" >> ${component}.js;
โ
# Creating File For Testing
echo "import React from 'react';
import { fireEvent, render, wait } from '@testing-library/react';
import $component from './$component';
โ
const setup = (customProps ={}) => {
const defaultProps = {};
const props = { ...defaultProps, ...customProps};
return render(<$component {...props}/>);
};
โ
beforeEach(() => {
jest.resetAllMocks();
});
โ
describe('$component', () => {
โ
it('should render the text $component in the document', () => {
const { getByText } = setup({ text: '$component' });
expect(getByText('$component')).toBeInTheDocument();
});
โ
});
" >> ${component}.test.js;
โ
cecho "===================================" $magenta
echo ""
cecho "Successfully created $component!" $magenta
echo ""
As I stated before, this assumes you want a component, test, and scss file to live in it's own directory, and also that you'd be using BEM for structuring your CSS classes.
I dropped the script (I named it create.sh
into the project root, then I added "create": "./create.sh"
to the package.json
scripts section so I could run npm run create
from the command line, one could easily use yarn
here too.