Search code examples
reactjstypescriptnpmbabeljscreate-react-app

Ensure react is imported in each create-react-app component for bundling


I am using a create-react-app TypeScript project as a base for a React component I will release as an independent package. To use the package externally, I must import React from 'react' in each component file. However, create-react-app uses a babel-transform that marks the React import as unnecessary. I want my environment to expect a React import where the modular code will demand it. How can I modify my create-react-app project to throw an error if React is not imported in every component?


Solution

  • I found a solution using tsconfig in a relevant issue in the typescript repository: https://github.com/microsoft/TypeScript/issues/41882#issuecomment-940734525

    The jsx compiler option needs to be set to "react", not "react-jsx":

    {
      "compilerOptions": {
        "jsx": "react"
      }
    }