Create React project using Typescript and Webpack
Update: As of 2018, many things have changed and better version of doing this is available at Typescript site itself: https://www.typescriptlang.org/docs/handbook/react-&-webpack.html
Pre-requisites
In order to follow the steps, typescript
, typings
, and webpack
must be first installed by following command:
npm install -g typescript typings webpack
Configure Project
1. Create a directory for your project and change directory into it.
2. Initialize Node package: npm init
3. Install React packages: npm install --save-dev react react-dom
(and redux react-redux
if you want to use it).
4. Install Webpack loader: npm install --save-dev webpack-bundle-tracker ts-loader source-map-loader
5. Link Typescript and Webpack from global to local:
npm link typescript
npm link webpack
5. Create a directory for your source. e.g. mkdir src
6. Create Typescript configuration file tsconfig.json
in the root of project directory.
{
"compilerOptions": {
"outDir": "./bundles/",
"sourceMap": true,
"noImplicitAny": false,
"module": "commonjs",
"target": "es2015",
"jsx": "react"
},
"exclude": [
"node_modules"
]
}
7. Create Typings configuration file typings.json
by issuing command typings init
. Then install React's related type definition by following command.
typings install --save --global dt~react dt~react-dom dt~react-redux dt~redux
8. Create Webpack configuration file webpack.config.js
var path = require('path')
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')
module.exports = {
context: __dirname,
entry: { main: ['./src/js/index.tsx'] },
output: {
path: path.resolve('./bundles'),
// or '[name]-[hash].js' if you can dynamically load JS, so you don't have to always invalidate cache.
filename: '[name].js'
},
devtool: 'source-map', // for debugging
plugins: [
new BundleTracker({filename: './webpack-stats.json'})
],
module: {
loaders: [
{ test: /\.tsx?$/, loader: 'ts-loader' }
],
preLoaders: [
{ test: /\.js$/, loader: 'source-map-loader' }
]
},
resolve: {
modulesDirectories: ['node_modules'],
extensions: ['', '.js', '.ts', '.tsx']
}
}
9. Create Typescript file src/js/index.tsx
with following content.
import * as React from 'react'
import * as ReactDOM from 'react-dom'
const HelloWorld = _ => <h1>Hello, world!</h1>
ReactDOM.render(<HelloWorld />, document.getElementById('content'))
Note that to use React in Typescript, the module react
must always be loaded.
10. Run webpack
to generate bundles/main.js
file.
11. Create index.html
and refer to the generated file.
<!DOCTYPE html>
<html>
<body>
<div id="content" />
<script type="text/javascript" src="bundles/main.js"></script>
</body>
</html>
12. Open index.html
on a browser and that's it!