In the previous posts we saw on how to create React Applications using
JavaScript and JSX. We can also write react applications using TypeScript. The
build environment setup will be different when we use TypeScript.
When we created React Applications using JavaScript (ES6) we used the Bable loaders to transpile ES6 code into browser compatible JavaScript code, in case of TypeScript we will have to use a TypeScript loader (ts-loader) instead of Bable. In this post we shall see in details on how to setup the environment for creating React applications using TypeScript.
First to start with let us create a new project by running npm init
When we created React Applications using JavaScript (ES6) we used the Bable loaders to transpile ES6 code into browser compatible JavaScript code, in case of TypeScript we will have to use a TypeScript loader (ts-loader) instead of Bable. In this post we shall see in details on how to setup the environment for creating React applications using TypeScript.
First to start with let us create a new project by running npm init
Provide appropriate details to the prompts and this will create a new project.json file, next let us install webpack npm packages as follows.
npm install webpack --save-dev
npm install webpack-cli --save-dev
Next install the react react-dom npm packages, also react is written in JavaScript and it does not include the type definitions for TypeScript, so additionally we need to install @types/react & @types/react-dom packages for TypeScript.
npm install react react-dom --save
npm install @types/react @types/react-dom --save-dev
Next we will install the typescript and type-script loader packages required to transpile TypeScript into native JavaScript supported by browsers.
npm install typescript ts-loader source-map-loader --save-dev
The TypeScript loader ts-loader package uses the TypeScript configuration file tsconfig.json to transpile TypeScript code into native JavaScript code, web-pack uses ts-loader to perform this conversion. The TypeScript config file will be as follows.
{
"compilerOptions":
{
"outDir": "./dist/",
"sourceMap":
true,
"noImplicitAny": true,
"module":
"commonjs",
"target":
"es6",
"jsx":
"react"
}
}
Next let us create the config file for Webpack webpack.config.js as follows.
module.exports = {
mode: "production",
devtool:
"source-map",
resolve: {
extensions:
[".ts", ".tsx"]
},
module: {
rules: [
{
test:
/\.ts(x?)$/,
exclude:
/node_modules/,
use: [
{
loader:
"ts-loader"
}
]
},
{
enforce:
"pre",
test: /\.js$/,
loader:
"source-map-loader"
}
]
},
externals: {
"react":
"React",
"react-dom":
"ReactDOM"
}
};
That’s it we are done with the environment setup
to develop React applications using TypeScript, in the next post let’s create a
Hello World React application using this TypeScript – React environment setup.
1 comment:
Good to know the webpack and type script.
Visual Foxpro to .Net and Visual Foxpro Migration
Post a Comment