Create a React project from scratch, with TypeScript and Webpack

A step by step guide on how to create a React project from scratch, with TypeScript and Webpack 5.

Setup

Prerequisites:

node
yarn

Create the project’s folder:

mkdir react-app
cd react-app

Generate a default package.json file with…


This content originally appeared on DEV Community and was authored by Alex Adam

A step by step guide on how to create a React project from scratch, with TypeScript and Webpack 5.

Setup

Prerequisites:

  • node
  • yarn

Create the project's folder:

mkdir react-app
cd react-app

Generate a default package.json file with yarn:

yarn init -y

Install React, TypeScript and Webpack:

yarn add react react-dom

yarn add --dev @types/react \
        @types/react-dom \
        awesome-typescript-loader \
        css-loader \
        html-webpack-plugin \
        node-sass \
        sass-loader \
        style-loader \
        typescript \
        webpack \
        webpack-cli \
        webpack-dev-server

Add build, dev & clean scripts in the package.json file:

 ....
  },
  "scripts": {
    "clean": "rm -rf dist/*",
    "build": "webpack",
    "dev": "webpack serve"
  }

Configure TypeScript by creating the file tsconfig.json with:

{
  "compilerOptions": {
    "incremental": true,
    "target": "es5",
    "module": "commonjs",
    "lib": ["dom", "dom.iterable", "es6"],
    "allowJs": true,
    "jsx": "react",
    "sourceMap": true,
    "outDir": "./dist/",
    "rootDir": ".",
    "removeComments": true,
    "strict": true,
    "moduleResolution": "node",            
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "experimentalDecorators": true
  },
  "include": [
    "client"
  ],
  "exclude": [
    "node_modules",
    "build",
    "dist"
  ]
}

To configure Webpack, make a file webpack.config.js containing:

const path = require("path");

const app_dir = __dirname + '/client';

const HtmlWebpackPlugin = require('html-webpack-plugin');
const HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
  template: app_dir + '/index.html',
  filename: 'index.html',
  inject: 'body'
});

const config = {
  mode: 'development',
  entry: app_dir + '/app.tsx',
  output: {
    path: __dirname + '/dist',
    filename: 'app.js',
    publicPath: '/'
  },
  module: {
    rules: [{
        test: /\.s?css$/,
        use: [
          'style-loader',
          'css-loader',
          'sass-loader'
        ]
      }, {
        test: /\.tsx?$/,
        loader: "awesome-typescript-loader",
        exclude: /(node_modules|bower_components)/
      },
      {
        test: /\.(woff|woff2|ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        exclude: [/node_modules/],
        loader: "file-loader"
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        exclude: [/node_modules/],
        loader: "file-loader"
      },
      {
        test: /\.(pdf)$/i,
        exclude: [/node_modules/],
        loader: "file-loader",
        options: {
          name: '[name].[ext]',
        },
      },
    ]
  },
  plugins: [HTMLWebpackPluginConfig],
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".jsx"]
  },
  optimization: {
    removeAvailableModules: false,
    removeEmptyChunks: false,
    splitChunks: false,
  },
  devServer: {
    port: 8080,
    // open: true,
    hot: true,
    inline: true,
    historyApiFallback: true,
  },
};
module.exports = config;

Example App

Create a folder named client (in the project's folder):

mkdir client
cd client

Make a simple React component, in the file numbers.tsx:

import React, {useState} from 'react';

interface INumberProps {
  initValue: number
}

const Numbers = (props: INumberProps) => {
  const [value, setValue] = useState(props.initValue)

  const onIncrement = () => {
    setValue(value + 1)
  }

  const onDecrement = () => {
    setValue(value - 1)
  }

  return (
    <div>
      Number is {value}
        <div>
          <button onClick={onIncrement}>+</button>
          <button onClick={onDecrement}>-</button>
        </div>
    </div>
  )
}
export default Numbers

Create the main React component (the entry point), in the file app.tsx:

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import Numbers from './numbers';

ReactDOM.render(
    <Numbers initValue={42} />,
    document.getElementById('app') as HTMLElement
  );

Next, add the index.html:







  React TypeScript





<p><br>
</p>
<pre class="highlight plaintext"><code>


Then, run `yarn dev` and open `http://localhost:8080/` in a browser.

## Use this project as a template

You can save the *Setup* steps as a shell script:



```sh
#!/bin/sh

rm -rf node_modules
rm package.json

yarn init --yes

yarn add react react-dom

yarn add --dev @types/react \
        @types/react-dom \
        awesome-typescript-loader \
        css-loader \
        html-webpack-plugin \
        node-sass \
        sass-loader \
        style-loader \
        typescript \
        webpack \
        webpack-cli \
        webpack-dev-server

# Remove the last line
sed -i.bak '$ d' package.json &amp;&amp; rm package.json.bak

# append the scripts commads
cat &lt;&lt;EOT &gt;&gt; package.json
   ,"scripts": {
      "clean": "rm -rf dist/*",
      "build": "webpack",
      "dev": "webpack serve"
   }
}
</code></pre>
<p></p>

<p>Delete the <strong>node-modules</strong> folder and, when you want to start a new project, you can copy the contents of <em>react-app</em> to the new location:<br>
</p>
<pre class="highlight shell"><code><span class="nb">mkdir </span>new-project
<span class="nb">cd </span>new-project

<span class="c"># copy the react-app folder content to the new project</span>
rsync <span class="nt">-rtv</span> /path/to/../react-app/ <span class="nb">.</span>

./init.sh
</code></pre>
<p></p>


This content originally appeared on DEV Community and was authored by Alex Adam


Print Share Comment Cite Upload Translate Updates
APA

Alex Adam | Sciencx (2021-05-22T14:53:26+00:00) Create a React project from scratch, with TypeScript and Webpack. Retrieved from https://www.scien.cx/2021/05/22/create-a-react-project-from-scratch-with-typescript-and-webpack/

MLA
" » Create a React project from scratch, with TypeScript and Webpack." Alex Adam | Sciencx - Saturday May 22, 2021, https://www.scien.cx/2021/05/22/create-a-react-project-from-scratch-with-typescript-and-webpack/
HARVARD
Alex Adam | Sciencx Saturday May 22, 2021 » Create a React project from scratch, with TypeScript and Webpack., viewed ,<https://www.scien.cx/2021/05/22/create-a-react-project-from-scratch-with-typescript-and-webpack/>
VANCOUVER
Alex Adam | Sciencx - » Create a React project from scratch, with TypeScript and Webpack. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/05/22/create-a-react-project-from-scratch-with-typescript-and-webpack/
CHICAGO
" » Create a React project from scratch, with TypeScript and Webpack." Alex Adam | Sciencx - Accessed . https://www.scien.cx/2021/05/22/create-a-react-project-from-scratch-with-typescript-and-webpack/
IEEE
" » Create a React project from scratch, with TypeScript and Webpack." Alex Adam | Sciencx [Online]. Available: https://www.scien.cx/2021/05/22/create-a-react-project-from-scratch-with-typescript-and-webpack/. [Accessed: ]
rf:citation
» Create a React project from scratch, with TypeScript and Webpack | Alex Adam | Sciencx | https://www.scien.cx/2021/05/22/create-a-react-project-from-scratch-with-typescript-and-webpack/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.