Categories
Web Development

How to use Google Typescript Style Guide in a ReactJS project

gts is Google’s TypeScript style guide, and the configuration for formatter, linter, and automatic code fixer. No lint rules to edit, no configuration to update, no more bike shedding over syntax. there are a few configurations to use it in a ReactJS project and I logged here:

1. Create a new React project with the TypeScript template

%npx create-react-app client-demo --template typescript
%cd client-demo
%yarn

2. Add and initiate gts into the project

Before adding gts, please backup your tsconfig.json file because gts will generate a new one overwriting it.

Execute the below command, it will prompt if you want to overwrite the existing “tsconfig.json”, just select “y” here.

%npx gts init

We have installed ReactJS and gts in our project, however, if you try starting the project with “yarn start” now, you will encounter the below error due to the eslint setting conflicts between reactjs and gts, we need to do some extra work to solve it.

3. Restore tsconfig.json changed by gts

The tsconfig.json file overwritten by gts is like this:

{
  "extends": "./node_modules/gts/tsconfig-google.json",
  "compilerOptions": {
    "rootDir": ".",
    "outDir": "build"
  },
  "include": [
    "src/**/*.ts",
    "test/**/*.ts"
  ]
}

Replace the above with our backup file, just keep the first “extends” line,

{
  "extends": "./node_modules/gts/tsconfig-google.json",
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}

4. Eslint settings

Install required eslint plugins:

%yarn add -D eslint-plugin-react eslint-plugin-node eslint-plugin-prettier

Update eslintrc.json:

/* This is original created by gts */
{
  "extends": "./node_modules/gts/"
}

To:

{
  "extends": [
    "./node_modules/gts/",
    "plugin:react/recommended"
  ],
  "env": {
    "browser": true,
    "jest": true
  }
}

Now, you have completed all the above four-step settings and can run ReactJS successfully.


There is one more optional setting I would recommend is adding husky pre-commit check so the system will execute gts check automatically when committing your code every time.

1. Install husky

npx husky-init && yarn

2. Edit “./husky/pre-commit” file

Replace "npm test" as "./node_modules/.bin/gts check"

All done, now the system will do “gts check” before committing your code.

Thanks for reading, please comment and let me know if you have any questions.

Leave a Reply

Your email address will not be published.