Search code examples
reactjstypescriptcreate-react-appparsing-errortypescript-eslint

Typescript parsing error when EXTEND_ESLINT=true in create-react-app


Stripped down demonstration - GitHub

We currently have a create-react-app project that is undergoing an incremental migration from Flow to Typescript. This meant disabling some undesirable ESLint rules. In order to customise ESLint, I've added EXTEND_ESLINT=true to the .env file.

Before adding this setting, my Typescript code compiles fine. Afterwards, I get parsing errors on certain (but not all) Typescript grammars.

// Type guards
export function f0<T>(x: T|undefined): x is T { ...

// Constrained generics
export function f1<T extends number>(x: T) { ...

// Type assertions
... return x as T

There may be other unrecognised syntaxes I haven't found yet.

So far

Solutions

  • Ejecting is not an option. If no other solution can be found, I would rather just do the Flow -> TS conversion in one go.

  • We currently extend our CRA configuration with customize-cra. Solutions involving this are welcome.

  • I enjoy the flexibility the .eslintrc gives me but I am happy to do away with it, provided I can still set lint rules.

Notes

  • I've included customize-cra in the demo repo to accurately reflect our project, but the problem persists without customize-cra, indicating that it is likely not the culprit.

  • See src/components/TestComponent/fn.ts for examples of the problem syntax.

  • My current hypothesis is that there's some setup in the CRA ESLint config that doesn't get carried over when EXTEND_ESLINT=true.

Updates


Solution

  • UPDATE: Update react-scripts to latest version at least 3.4.1. It's fixed.

    For pre 3.4.1 versions of react-scripts,

    Open node_modules/react-scripts/config/webpack.config.js

    Replace code block from line 365 with this code.

      if (process.env.EXTEND_ESLINT === 'true') {
        return undefined
      } else {
        return {
          extends: [require.resolve('eslint-config-react-app')],
        };
      }
    })(),
    useEslintrc: process.env.EXTEND_ESLINT === 'true',
    

    Now if you start your app by yarn or npm, you will see it is fixed.

    The fix is originally introduced here

    https://github.com/facebook/create-react-app/issues/7776#issuecomment-567587642

    Run npx patch-package react-scripts to make a patch for it. And add "postinstall": "patch-package" to your package.json scripts section.

    The patch will be automatically applied after npm install