This is my workflow when I set up a new project, it should only take a few minutes to get everything up and running.
Create React App
The easiest way to create a new React project is to use the create react app, and you can easily have it set up with TypeScript too.
npx create-react-app my-app --template typescript
# or
yarn create react-app my-app --template typescript
ESLint
Next, you will want to install ESLint, and plugins for TypeScript:
yarn add -D eslint eslint-plugin-react @typescript-eslint/eslint-plugin @typescript-eslint/parser
Then in your project directory, create .eslintrc.js
:
module.exports = {
parser: '@typescript-eslint/parser',
extends: [
'plugin:react/recommended',
'plugin:@typescript-eslint/recommended',
],
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
jsx: true,
},
},
rules: {},
settings: {
react: {
version: 'detect', // Tells eslint-plugin-react to automatically detect the version of React to use
},
},
env: {
jest: true,
},
};
Now, you will have basic linting rules for TS:
Prettier
Install Prettier for formatting your code:
yarn add -D prettier eslint-plugin-prettier eslint-config-prettier
Create .prettierrc.json
, and add the following:
{
"trailingComma": "es5",
"printWidth": 100,
"semi": true,
"singleQuote": true
}
Then modify the eslintrc.js
, and add these two lines:
extends: [
...
'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
'plugin:prettier/recommended', // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
],
With the Prettier extension installed in VS Code, it will show any formatting errors:
VS Code
I would recommend turning on formatOnSave
, and fix all ESLint error on save, to make your life even easier:
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
}
Finally
I hope you found it useful, please let know if you have any feedback.
Top comments (1)
Nice! Just wanted to mention another alternative to CRA in case you weren’t aware, TSDX.
It was created by Jared Palmer and it’s endorsed by the TypeScript team. It handles multiple project types including React.
jaredpalmer / tsdx
Zero-config CLI for TypeScript package development
Despite all the recent hype, setting up a new TypeScript (x React) library can be tough. Between Rollup, Jest,
tsconfig
, Yarn resolutions, ESLint, and getting VSCode to play nicely....there is just a whole lot of stuff to do (and things to screw up). TSDX is a zero-config CLI that helps you develop, test, and publish modern TypeScript packages with ease--so you can focus on your awesome new library and not waste another afternoon on the configuration.Features
TSDX…
Looking forward to your next post!