Generating a TypeScript project

At this point in the chapter, you might be worried (or sad) about not seeing TypeScript code for so long. Don't panic just yet though; we're just getting started! We first wanted to present vanilla React code before adding TypeScript to the mix.

The first good news that we can give you is that CRA supports generating TypeScript-enabled React applications.

It is as simple as adding the --typescript flag to the create-react-app command:

npx create-react-app my-app --typescript 

React applications created in this way exhibit some differences from what we've shown before.

First of all, they have a tsconfig.json file that looks as follows:

{ 
  "compilerOptions": { 
    "target": "es5", 
    "lib": [ 
      "dom", 
      "dom.iterable", 
      "esnext" 
    ], 
    "allowJs": true, 
    "skipLibCheck": true, 
    "esModuleInterop": true, 
    "allowSyntheticDefaultImports": true, 
    "strict": true, 
    "forceConsistentCasingInFileNames": true, 
    "module": "esnext", 
    "moduleResolution": "node", 
    "resolveJsonModule": true, 
    "isolatedModules": true, 
    "noEmit": true, 
    "jsx": "react" 
  }, 
  "include": [ 
    "src" 
  ] 
} 

In this configuration file, there is an interesting option that we haven't encountered so far: jsx. Its name should give you a hint about what is coming next!

Also, note that the file containing the App component now has a .tsx extension. Indeed, as we'll see right after, TypeScript has built-in support for JSX! We'll explore the code in a jiffy.

Finally, if you take a look at the package.json file, you'll see that TypeScript typings have been added for react, react-dom, and jest.

With Visual Studio Code and IntelliJ/WebStorm, you can debug your code directly in the editor: https://facebook.github.io/create-react-app/docs/setting-up-your-editor#debugging-in-the-editor.

You can find an example project in the assets of this book, under Chapter11/10-create-react-app-typescript.

For further reference, check out the following: https://create-react-app.dev/docs/adding-typescript.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.71.237