React with Typescript is part 2 of a 5 parts React with ASP.NET Core series. This series will show you the setup necessary for building React single page application with routing and server-side rendering.
When I first dived into migrating from traditional server side rendering towards more focus on client side rendering using React, one major decision to make was to whether go with javascript or typescript. The confusion at the time was really why we need another layer of technology on the already familiar javascript we have been using for many years. Isn’t client side rendering already much more complicated than we want already and here we have another layer of complexity.
Why Typescript
Check TypeScript Deep Dive out as for Why TypeScript. It also has a lot of other resources about Typescript.
I have been using many strongly typed languages like C++, C#, Java, Swift for many years and also enjoy the flexibility javascript provides. While still with some skepticism, I decided to move forward with Typescript. I haven’t looked back.
We really benefit from catching a lot of errors/potential bugs during development with type checking. And more often than not, when we did hit some bugs, those are the break points when we were getting lazy and try to skip some type checking using the type any. That’s when we got those undefined objects and causing errors. While defining types in Typescript could be tedious and sometimes hard to comprehend when the types are complex, I preferred this tedious over those undefined objects or hidden bugs that could drag you for nights.
There were also a problem with types compatibility. There may be some older libraries you want to use but do not have type definitions. Or there could be type conflicts with Visual Studio’s Typescript support. These issues can drive you crazy. But Typescript support has since improved a lot and is getting better and better.
React with Typescript, Get Started
Goal: Use react with typescript to display a simple HelloWorld component.
The setup will base off on the example codes from part 1 React with ASP.NET Core, Get started using Visual Studio . With this base project codes, we can already run React components with ASP.NET Core with basic webpack settings. It has project structure as shown below:
First we enable Typescript for React. Then go to menu Menu Project > [Project name] Properties... , select TypeScript Build tab, and update as the screen shown:
Note: Both Visual Studio & webpack will compile typescript files (i.e. each file is compiled twice and Visual Studio compiled files are not used for bundling). We can stop Visual Studio from compiling typescript files. However, doing so will also disable syntax checking of typescript during editing. Not sure if there’s a way to get around this. If you want to keep syntax checking, skip to the next part.
To disable typescript compilation by Visual Studio, go to Project > Edit [Project name].csproj, add the following lines inside the Project tag.
1 2 3 |
<PropertyGroup> <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked> </PropertyGroup> |
Add Typescript version of HelloWorld
Create HelloWorld.tsx & entry.tsx, using file type Installed > Visual C# > ASP.NET Core > Web > TypeScript JSX File.
1 2 3 4 5 6 7 8 9 10 |
import * as React from 'react'; interface Props { } interface IState {} export class HelloWorld extends React.Component<Props, IState> { render() { return <div>Hello world using Typescript & React!</div>; } } |
1 2 3 4 5 |
import * as React from 'react'; import { render } from 'react-dom'; import { HelloWorld } from './HelloWorld'; render(<HelloWorld />, document.querySelector('body')); |
Update Webpack to handle Typescript
Add the two packages to package.json inside devDependencies
1 2 |
"typescript": "2.9.2", "ts-loader": "4.4.2" |
Webpack will use ts-loader to convert typescript files ( .tsx/.ts) to .jsx/.js format
Next ts-loader needs a typescript config file tsconfig.json. Add it under your project
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
{ "compilerOptions": { "outDir": "Scripts/_vsCompile", "noImplicitAny": false, "noEmitOnError": true, "removeComments": false, "sourceMap": true, "target": "es5", "jsx": "react", "lib": [ "es6", "dom" ] }, "exclude": [ "node_modules", "wwwroot" ] } |
Finally, modify the webpack.config.js as shown to use the ts-loader:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
"use strict"; const path = require('path'); module.exports = { mode: 'development', target: 'web', entry: { bundle: "./Scripts/entry.tsx" }, output: { path: path.resolve(__dirname, 'wwwroot/dist'), publicPath: '/dist/', // needed for UseWebpackDevMiddleware() filename: "[name].js" }, module: { rules: [ { test: /\.tsx{0,1}$/, loader: 'ts-loader', options: { configFile: 'tsconfig.json' } }, { test: /\.jsx$/, loader: 'babel-loader', query: { presets: ['react', ['env', { 'targets': { 'browsers': '> 5%' } }]] } } ] }, resolve: { extensions: ['.ts', '.tsx', '.jsx', '.js'] // with this, you don't need extension when importing modules } }; |
The project should now be ready to build and run react with typescript. (VS Build and Task Runner Explorer > Run - Development)
Example code for React with ASP.NET Core series – Part 2 is available at Github.
More Read
React with ASP.NET Core series – Part 3: React with Redux, Get started, with ASP.NET Core
React with ASP.NET Core series – Part 1: React with ASP.NET Core, Get started using Visual Studio