The tutorial for React and Webpack at typescriptlang.org is one of the better tutorials out there, although with the introduction of Webpack 4 and wanting the hot reload support, I sought to seek out a more modern tutorial. I found the tutorial at AppDividend but still wanted the familiar experience of the one at typescriptlang.org.
The credit of course goes to the authors of each respective article.
npm install -g typescript npm install -g webpack-cli
mkdir react-typescript-webpack4 cd react-typescript-webpack4
mkdir src cd src mkdir components cd ..
First initialise the project:
npm init -y
Next add the packages we'll need:
npm install webpack webpack-cli webpack-dev-server --save-dev npm install typescript ts-loader --save-dev npm install react react-dom @types/react @types/react-dom --save-dev
{ "compilerOptions": { "outDir": "./dist/", "sourceMap": true, "noImplicitAny": true, "module": "commonjs", "target": "es5", "jsx": "react" }, "include": [ "./src/**/*" ] }
const path = require('path');
module.exports = { entry: path.join(__dirname, '/src/index.tsx'), output: { filename: 'bundle.js', path: __dirname + "/dist", publicPath: "/dist/" }, module: { rules: [ { test: /\.tsx?$/, loader: 'ts-loader', exclude: /node_modules/, }, ] }, resolve: { extensions: [".tsx", ".ts", ".js"] }, // When importing a module whose path matches one of the following, just // assume a corresponding global variable exists and use that instead. // This is important because it allows us to avoid bundling all of our // dependencies, which allows browsers to cache those libraries between builds. externals: { "react": "React", "react-dom": "ReactDOM" }, };
Index.tsx
import * as React from "react"; import * as ReactDOM from "react-dom";
import { Hello } from "./components/Hello";
ReactDOM.render(
Hello.tsx
import * as React from "react";
export interface HelloProps { compiler: string; framework: string; }
// 'HelloProps' describes the shape of props. // State is never set so we use the '{}' type. export class Hello extends React.Component<HelloProps, {}> { render() { return
index.html
<!-- Dependencies -->
<script src="./node\_modules/react/umd/react.development.js"></script>
<script src="./node\_modules/react-dom/umd/react-dom.development.js"></script>
<!-- Main -->
<script src="./dist/bundle.js"></script>
</body>
Add the following "start" scrip to the scripts section in package.json to look as follows:
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack-dev-server --mode development" },