Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonybrown/84ffe9172b5d2202bffe800e57171d23 to your computer and use it in GitHub Desktop.
Save anthonybrown/84ffe9172b5d2202bffe800e57171d23 to your computer and use it in GitHub Desktop.
A script to create the boilerplate code for a new React.js component with a [Jest] spec file
#! /usr/bin/env node
# Usage: node create-react-component.js ComponentName
# Note: If a `components` directory does not exist in the current working directory, nothing will be created
const fs = require('fs')
const path = require('path')
const componentName = process.argv[2]
const componentPath = path.join(
'components',
componentName
)
let rollUpContent = `
import ${componentName} from './${componentName}'
export default ${componentName}
`.trimLeft()
let rollUpSpec = `
import DefaultExport from './index'
import ${componentName} from './${componentName}'
describe('${componentName} rollup', () => {
it('should export ${componentName} as the default class', () => {
expect(DefaultExport).toBe(${componentName})
})
})
`.trimLeft()
let componentContent = `
import React from 'react'
class ${componentName} extends React.Component {
render () {
return (
<div />
)
}
}
export default ${componentName}
`.trimLeft()
let componentSpec = `
import React from 'react'
import { shallow } from 'enzyme'
import ${componentName} from './index'
describe('<${componentName} />', () => {
it('should not render children', () => {
const wrapper = shallow(
<${componentName}>
<div className="unique" />
</${componentName}>
)
expect(wrapper.find('div.unique')).toHaveLength(0)
})
})
`.trimLeft()
fs.mkdir(componentPath, (error) => {
if (error) {
return console.log('Could not create the directory')
}
fs.writeFile(path.join(componentPath, 'index.jsx'), rollUpContent, (error) => {
if (error) {
console.log('Failed to create the rollup')
}
})
fs.writeFile(path.join(componentPath, 'index.spec.jsx'), rollUpSpec, (error) => {
if (error) {
console.log('Failed to create the rollup spec')
}
})
fs.writeFile(path.join(componentPath, `${componentName}.jsx`), componentContent, (error) => {
if (error) {
console.log('Failed to create the component')
}
})
fs.writeFile(path.join(componentPath, `${componentName}.spec.jsx`), componentSpec, (error) => {
if (error) {
console.log('Failed to create the component spec')
}
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment