How to setup React Typescript Project from scratch with Webpack
Create React App is no doubt a very good toolkit to build a basic react application. You simply run a single command (npx create-react-app your-project-name
)and it will setup the tools you need to start your React project. It is really helpful to start building react app for Beginners but as a Senior or Mid-Senior level developer you should have ability to create your own boilerplate. This article will teach you how to create your own boilerplate from base in react with typescript by using webpack.
Getting Started
Let's start by creating a new directory for our project
mkdir react-boilerplatecd react-boilerplate
Now initialize the project with npm
npm init -y
This command will create a package.json
file with some default values.
Adding React and Typescript
Add the following commands in order to install React and Typescript
npm install react react-dom -Snpm install typescript @types/react @types/react-dom -D
Typescript is configured by a file which is called tsconfig.json
. Let's add this file in the root directory of our project.
{ "compilerOptions": { "jsx": "react", "module": "commonjs", "noImplicitAny": true, "outDir": "./dist/", "preserveConstEnums": true, "removeComments": true, "sourceMap": true, "target": "es5" }, "include": [ "./src/index.tsx" ]}
Let's also look and understand the different options we added in this file.
compilerOptions
Represents the different compiler options.jsx:react
Adds support for JSX in.tsx
files.module
Generates module code.noImplicitAny
Raises errors for declarations with an impliedany
type.outDir
Represents the output directory.sourceMap
Generates a.map
file, which can be very useful for debugging the apptarget
Represents the target ECMAScript version to transpile our code down to specified version(we can add a version based on our specific browser requirements).include
Used to specify the file list to be included even we can specify folder here as well.
Adding Webpack
Webpack is a bundler which bundles all your javascript code and related dependencies into one bundle file (bundle.js
). Let's install webpack related dependencies.
npm install webpack webpack-cli webpack-dev-server -D
webpack
is a module bundler.webpack-cli
is a command line interface to run webpack related commands.webpack-dev-server
is a web server which watches our changes and refresh the web page when any changes is made to our component.
Now we need to add some loaders.
npm install ts-loader css-loader source-map-loader -D
ts-loader
loads any file which has extension.tsx
or.ts
css-loader
loads any file which has extension.css
source-map-loader
loads any file which has extension.js
You may learn more about loaders and use them if you need any according to your project requirement . We also need one more dependency html-webpack-plugin
which creates a template file that is rendered to the browser from index.html
npm install html-webpack-plugin -D
Now it's time to configure webpack in our project. Let's create a file webpack.config.js
in the root directory of our project
const path = require("path");const HtmlWebpackPlugin = require("html-webpack-plugin");module.exports = { entry: './src/index.tsx', output: { path: path.resolve(__dirname, "dist"), filename: "bundle.js", }, resolve: { extensions: [".js", ".jsx", ".json", ".ts", ".tsx"], }, module: { rules: [ { test: /\.(ts|tsx)$/, loader: "ts-loader", }, { enforce: "pre", test: /\.js$/, loader: "source-map-loader", }, { test: /\.css$/, loader: "css-loader", }, ], }, plugins: [ new HtmlWebpackPlugin({ template: path.resolve(__dirname, "src", "index.html"), }), ],}
Let's look at different options we have added in webpack.config.js
entry
This field specifies the entry point of our application.output
This field tells webpack where to bundle our code. Thepath
represents the output directory of the code andfilename
represent the filename where all the code will be bundled usually we call itbundle.js
resolve.extensions
This field specifies which type of files to look during module resolution.module
This field directed Webpack how different modules will be treated. For example, we are usingts-loader
to load.tsx
and.ts
types of file.plugins
This field usually work at the end of bundle generation process.
Adding
index.html
Create src
folder in the root directory and add index.html
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>React Boilerplate</title> </head> <body> <div id="root"></div> </body></html>
Adding Components
Lets create a component App.tsx
in src
folder
import * as React from 'react';const App = () => { return ( <h3> Welcome to React Boilerplate </h3> )}export default App;
Now let's add index.tsx
in the same folder which will be the entry point of our app.
import * as React from 'react';import { render } from 'react-dom';import App from './App';
render(<App />, document.getElementById('root'));
Adding npm scripts
Add the following scripts in package.json
file.
"scripts": { "start": "webpack serve --port 3000 --mode development --open --hot", "build": "webpack --mode production"}
If you are using webpack 4 or above it is recommended to use webpack serve
otherwise you can use webpack-dev-server
Run Application
Now let's run the script npm start
and your application will be ready.
If you want to build the project you can run npm run build
and you will see the folder dist
in the root directory and in this folder you will have bundle.js
and index.html
.
This repo has all the code which is used in this blog post. If you want you can clone the project and try to run it. If you found any difficulty you may write to me. I'd be very happy to help and please don't forget to star :)