5 Tips in CRA@2.0

Origin

It’s fucking long time not learning React.

Five Tips

  1. Displaying Lint Error in the Editor

Create .eslintrc with content of

1
2
3
{
"extends: "react-app"
}
  1. Formatting Code Automatically
1
npm install --save-dev prettier husky lint-staged

And add scripts in package.json

1
2
3
4
5
6
7
8
9
10
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"src/**/*.{js,jsx,json,css}": ["prettier --write", "git add"]
}
}

I prefer to use prettier with eslint

  1. Developing Components in Isolation

I use bit

  1. Making a Progressive Web App

In src/index.js, change serviceWorker.unregister() to serviceWorker.register()

  1. Code Splitting

Create React App v2 supports code splitting via dynamic import() statements. That is, if it encouters a call to import('./someModule') when building your app, it will create a new chunk for someModule and all its dependencies, totally seperate from your entry bundle.

1
2
3
4
5
6
7
8
9
10
11
import React, { Component } from 'react'
import { Formik } from 'formik'
import * as Yup from 'yup'

const formValidator = Yup.object().shape(/* ... */)

export default class Form extends Component {
render() {
return <Formik validationSchema={formValidator}>{/* ... */}</Formik>
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import React, { Component } from 'react'

export default class App extends Component {
state = {
Form: undefined,
}

showForm = async () => {
const { default: Form } = await import('./Form')
this.setState({ Form })
}
render() {
const { Form } = this.state
return <div className="app">{Form ? <Form /> : <button onClick={this.showForm}>Show Form</button>}</div>
}
}

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×