Setup react with typescript

Setup React Application using Typescript and Webpack

In this post we will learn how to add support of TypeScript to your React Js application having webpack and babel configured. Please note that in this post I’m going to modify previously setup React Js application to add support for TypeScript. If you haven’t yet gone through that post then please start with Setup Webpack and Babel for a React Js Application and come back to this post.

Why Typescript?

According to official documentation, TypeScript is a strongly typed superset of JavaScript which uses TypeScript Compiler to compile it into plain JavaScript. TypeScript provide pure Object Oriented implementation to use classes, interfaces and inheritance. TypeScript check error in code at compile time and if any error found, then it shows the mistakes before the script is run. Also it support all existing JavaScript library as it is a superset of JavaScript. It make development quick and easy as possible and developers can save lot of time.

Installations

We need to install some packages which are essential to configure TypeScript in React application. Run below commands to install required packages:

npm install -D typescript ts-loader @types/node @types/react @types/react-dom 
  • typescript package is main engine for TypeScript.
  • ts-loader is loader for Webpack that integrates TypeScript in Webpack. This will convert files with .ts extension into .js files and bundle it.
  • @types/node, @types/react and @types/react-dom contains the type definitions required for node, react and react dom.
Читайте также:  Css attributes and values

Configuring Typescript

Add tsconfig.json file to the root directory location where package.json exists. Name should be exact same as mentioned and the below configurations into it.

Configuring Webpack

Webpack need to be configured to have support for TypeScript files. Here is small change you need to add in webpack.config.js

Add ts-loader (loader) and test for _ts _and _tsx _files.

add Test for .ts and .tsx extension to resolve:

//_webpack.config.js_ . resolve: < extensions: [ '.tsx', '.ts', '.js' ], >. 

And one final change in webpack config is to rename the _js _files to _tsx _in your react application and update the entry point

//_webpack.config.js_ . entry: "./src/index.tsx", . 

Testing Working for Typescript with React

To test the application, we create one component App which will take one prop of type number which will get passed by index.tsx

//_index.tsx_ import React from "react"; import ReactDOM from "react-dom"; import "./style.css"; import < App >from "./components/App"; ReactDOM.render( />, document.getElementById("root")); 
//components/App.tsx import React from "react"; type AppProps = < num: number >; export const App = (: AppProps) => Total Number: ; 

Boo-yah!😍 We are all set with TypeScript❤️.

typescript

Now just try to change the value which we were passing through props.

For example I’ll just change number 1234 to string “1234” and check what will happen.

error

As expected, Intellisense will show error like this so that we will identify it before building application. Isn’t it a great thing!

Also if we try to build it, command prompt will show error like this:

error_in_cmd

Error are self explanatory so that we can easily identify mistakes and correct it.

Conclusion

In this blog post we successfully configured TypeScript with React application and tested if it works properly or not.

Please do share your feedback and experiences with TypeScript in the comments section below. I’d love to see what you come up with!

If you found this article useful, please share it with your friends and colleagues!❤️

Read more articles on Dev.To ➡️ Shivam Pawar

Источник

Adding TypeScript

Note: this feature is available with react-scripts@2.1.0 and higher.

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.

Installation​

To start a new Create React App project with TypeScript, you can run:

npx create-react-app my-app --template typescript 
yarn create react-app my-app --template typescript 

If you’ve previously installed create-react-app globally via npm install -g create-react-app , we recommend you uninstall the package using npm uninstall -g create-react-app or yarn global remove create-react-app to ensure that npx always uses the latest version.

Global installs of create-react-app are no longer supported.

To add TypeScript to an existing Create React App project, first install it:

npm install --save typescript @types/node @types/react @types/react-dom @types/jest 
yarn add typescript @types/node @types/react @types/react-dom @types/jest 

Next, rename any file to be a TypeScript file (e.g. src/index.js to src/index.tsx ) and restart your development server!

Type errors will show up in the same console as the build one. You’ll have to fix these type errors before you continue development or build your project. For advanced configuration, see here.

Getting Started with TypeScript and React​

You are not required to make a tsconfig.json file, one will be made for you. You are allowed to edit the generated TypeScript configuration.

Troubleshooting​

If your project is not created with TypeScript enabled, npx may be using a cached version of create-react-app . Remove previously installed versions with npm uninstall -g create-react-app or yarn global remove create-react-app (see #6119).

If you are currently using create-react-app-typescript, see this blog post for instructions on how to migrate to Create React App.

Constant enums and namespaces are not supported, you can learn about the constraints of using Babel with TypeScript here.

Источник

How to Setup a React App with TypeScript + Webpack from Scratch

Have you ever created a React application using Create React App but was then curious about how it was configured under the hood? Do you want to use React with TypeScript, but have had a hard time finding all the setup instructions in one place? Do you prefer to avoid Babel for bundling or transpiling or want a more modern option like Webpack? This guide walks you through how to setup a React application with TypeScript-written components and bundled with Webpack. Bonus: It also teaches you how to configure Jest for testing.

🙋🏽 Why?

While Create React App is a great way to jump start a simple project, it unfortunately abstracts away most of the configuration in order to streamline the setup process. Should you ever want to customize a particular project configuration or be more aware of installed dependencies, you’ll have to manually wade through all of the pre-build configuration files and inspect each setting to learn what is required and what is optional. Create React App even hints at this on their homepage.

If you ever want an advanced configuration, you can ”eject” from Create React App and edit their config files directly.

While this is taunted as a «feature», it makes it more likely that developers will keep using the de facto Create React App tech stack and not make conscious decisions on what frameworks and libraries work best for the project requirements. Understanding how a React application is built from the ground up provides the developer the expertise to know when to use a cookie cutter template and when to forge their own path.

🧱 How?

This guide assumes that you have git , a Node package manager (e.g. npm , yarn ), your favorite IDE (e.g. VSCode, WebStorm), and the ability to run commands in a *nix-like terminal. Each step shows an example file to use as a starting point. are used in the examples to highlight values that needs to be updated with information specific to the project.

1. Initialize Project

Let’s start off by creating the initial project files. This will get the project ready for version control (e.g. GitHub) and dependency management (e.g. npm ).

  1. Create a new directory for your React application (e.g. my-react-app )
  2. Initialize a git repository to start the git history.
  • : A string that typically matches the name of the GitHub repository. See limitations for that value in package.json docs > name
  • : A string that concisely describes what your project is or does.
  • : The GitHub username or organization that will own the project’s repository.
  • : Strings to make your project more discoverable. They can be the same as the GitHub topics you apply to the repository.
  • : The person or organization writing the code
  • : The type of license to apply to this project.

Be sure to check out Take Your Github Repository To The Next Level. The sections on discoverability, naming, writing descriptions and choosing the right license should help you choose appropriate values for these placeholders for this and future projects.

2. Setup TypeScript

The Setup TypeScript PR shows the suggested state after completing these steps.

npm install --save-dev typescript ts-node @types/node 

With TypeScript configured, we are ready to add our first React components.

3. Setup React

The Setup React PR shows the suggested state after completing these steps.

npm install react react-dom npm install --save-dev @types/react @types/react-dom 

We now have a sample React app, ready for unit testing.

4. Setup Jest

The Setup Jest PR shows the suggested state after completing these steps.

npm install --save-dev jest ts-jest jest-environment-jsdom @types/jest @testing-library/jest-dom @testing-library/react 
"scripts":  "test": "jest", "test:watch": "jest --watch", "test:coverage": "jest --coverage" >, 
npm run test # Run the full test suite once npm run test:watch # Watch files for changes and rerun tests related to changed files npm run test:coverage # Generate and display a test coverage report 

Even though we cannot view the components in a browser yet, we can simulate a DOM during tests and verify content rendering. We’ll need a bundler to transpile our app into something a browser can display.

5. Setup Webpack

The Setup Webpack PR shows the suggested state after completing these steps.

  1. Install the Webpack dependencies required to serve files locally and bundle for production deployment.
npm install --save-dev webpack webpack-cli webpack-dev-server style-loader css-loader ts-loader html-webpack-plugin copy-webpack-plugin webpack-merge 
"scripts":  "build": "webpack --config webpack.production.js", "start": "webpack serve --config webpack.development.js", "test": "jest", #  Already in file from last step >, 
npm run start # Start a local development web server at http://localhost:8080 using webpack-dev-server npm run build # Bundle application for Production using webpack 

Now you can make changes to the components’ source code and view content locally in a browser. And once bundled, the app is ready for deployment to a remote server.

6. (Optional) Setup Tailwind CSS

The (Optional) Setup Tailwind CSS PR shows the suggested state after completing these steps.

  1. Install the Tailwind CSS dependencies required to import its utility styles and integrate with Webpack.
npm install --save-dev tailwindcss @types/tailwindcss postcss postcss-loader autoprefixer 
 test: /\.css$/i, use: ['style-loader', 'css-loader', 'postcss-loader'], >, 
@tailwind base; @tailwind components; @tailwind utilities; 

From here you can either create new components using Tailwind classes or migrate existing styles into the Tailwind framework. See the CSS file changes in the (Optional) Setup Tailwind CSS PR for an example of a style migration.

Summary

With TypeScript, Jest, and Webpack configured and React installed the project should be in a state equivalent to running npx create-react-app .

More specifically, you should be able to:

  • Develop React Components using TypeScript (using .tsx files)
  • Test React Components using Jest
  • Bundle a React Web Application for Production
  • Serve a React Web Application locally with automatic reloads on save
  • (Optional) Build custom design systems using Tailwind CSS utility classes

Be sure to check out the detailed tooling list for more information about the tech stack and dependencies used for this project template.

Источник

Оцените статью