Optimizing Your React App: A Guide to Production-Ready Setup with Webpack, TypeScript, ESLint, and Prettier - 2024
Tags: react, learning, webpack, typescript
Published: 2024-06-30 15:08:11

In this blog post, we'll cover everything you need to know to set up a React app that's ready for deployment.

GitHub Repo: https://github.com/shivam-pawar/sample-react-app 

## Prerequisites
Before we begin, make sure you have Node.js and npm (or yarn) installed on your machine.

## Initialize a new project
Use your Command Line and navigate to the root folder of your project and enter

```bash
npm init
```
This will ask you some basic information like package name, author name, description, and license. With this info it will create a file called _package.json_

## Install React and TypeScript

- Install React and ReactDOM as dependencies:

```bash
npm install react react-dom
```

- Install TypeScript and its types as dev dependencies:

```bash
npm install --save-dev typescript @types/react @types/react-dom
```

## Set up Webpack

Install the necessary Webpack dependencies:

```bash
npm install --save-dev webpack webpack-cli webpack-dev-server html-webpack-plugin webpack-merge ts-loader terser-webpack-plugin uglify-js
```
Your _package.json_ will look like this:


![package.json](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7xdvw39k9dnq3fw2mdns.png)

- Create a **webpack** folder at root/project level and inside that add these 3 config files.
   1. _webpack.common.js_
   2. _webpack.config.js_
   3. _webpack.dev.js_
   4. _webpack.prod.js_

- Create a *src* folder at root/project level and inside that add these 2 files.
   1. _index.tsx_
   2. _index.html_

- Copy paste below code in _index.tsx_

```typescript
import React from "react";
import { createRoot } from "react-dom/client";

const App = () => {
  return <div>Hello, React!</div>;
};

const rootElement = document.getElementById("root") as Element;
const root = createRoot(rootElement);

root.render(<App />);

```

- Copy paste below code in _index.html_

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My React App</title>
</head>
<body>
  <div id="root"></div>
</body>
</html>
```

Now lets update the webpack config files.

- _webpack.common.js_

```js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: path.resolve(__dirname, "..", "./src/index.tsx"),
  output: {
    path: path.resolve(__dirname, "..", "dist"),
    filename: "bundle.js",
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js"],
  },
  module: {
    rules: [
      {
        test: /\.(ts|js)x?$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "..", "./src/index.html"),
    }),
  ],
  devServer: {
    static: "./dist",
  },
};

```

- _webpack.config.js_

```js
const { merge } = require("webpack-merge");
const commonConfig = require("./webpack.common");

module.exports = (envVars) => {
  const { env } = envVars;
  const envConfig = require(`./webpack.${env}.js`);
  const config = merge(commonConfig, envConfig);
  return config;
};

```

- _webpack.dev.js_

```js
const webpack = require("webpack");

module.exports = {
  mode: "development",
  devtool: "cheap-module-source-map",
  devServer: {
    hot: true,
    open: true,
  },
  plugins: [
    new webpack.DefinePlugin({
      "process.env.name": JSON.stringify("development"),
    }),
  ],
};

```
- _webpack.prod.js_

```js
const webpack = require("webpack");
const TerserPlugin = require("terser-webpack-plugin");

module.exports = {
  mode: "production",
  devtool: false,
  plugins: [
    new webpack.DefinePlugin({
      "process.env.name": JSON.stringify("production"),
    }),
  ],
  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        minify: TerserPlugin.uglifyJsMinify,
        extractComments: true,
        parallel: true,
        test: /\.(ts|js)x?$/,
        terserOptions: {
          compress: {
            drop_console: true,
          },
          output: {
            comments: false,
          },
        },
      }),
    ],
  },
};
```

- Update/replace the scripts section in your _package.json_ file:

```json
"scripts": {
    "start": "webpack serve --config webpack/webpack.config.js --env env=dev",
    "build": "webpack --config webpack/webpack.config.js --env env=prod"
  }
```

## Setup TypeScript

At root/project level add _tsconfig.json_ file and paste below config in it.

```json
{
  "compilerOptions": {
    "target": "ES6",                                  
    "lib": [
      "DOM",
      "ESNext"
    ],                                        
    "jsx": "react-jsx",                               
    "module": "ESNext",                               
    "moduleResolution": "Node",                     
    "types": ["react", "react-dom", "@types/react", "@types/react-dom"],                                      
    "resolveJsonModule": true,                       
    "isolatedModules": true,                          
    "esModuleInterop": true,                            
    "forceConsistentCasingInFileNames": true,            
    "strict": true,                                      
    "skipLibCheck": true                                
  }
}

```

Now your project folder and file structure will look like this:

![Project Structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xv09qm37lomkv4z6gasv.png)

## Run the development server

In terminal/command prompt run below command to run your development server:

```bash
npm start
```

Your React app should now be running at _http://localhost:8080_.

## Set up ESLint and Prettier

- Install ESLint, Prettier, and the necessary plugins:

```bash
npm install --save-dev eslint eslint-config-prettier eslint-plugin-prettier @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-plugin-react
```

- Create an _.eslintrc.json_ file in the root of your project with the following configuration:

```json
{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:@typescript-eslint/recommended",
    "prettier"
  ],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": 12,
    "sourceType": "module"
  },
  "plugins": [
    "react",
    "@typescript-eslint",
    "prettier"
  ],
  "rules": {
    "prettier/prettier": "error"
  }
}
```

- Create a _.prettierrc_ file in the root of your project with the following configuration:

```json
{
  "semi": true,
  "trailingComma": "all",
  "singleQuote": false,
  "printWidth": 100,
  "tabWidth": 2
}
```

- Update the _scripts_ section in your _package.json_ file:

```json
"scripts": {
    "start": "webpack serve --config webpack/webpack.config.js --env env=dev",
    "build": "webpack --config webpack/webpack.config.js --env env=prod",
    "lint": "eslint . --ext .ts,.tsx --fix"
  }
```

- Run ESLint to check for any linting issues:

```bash
npm run lint
```

Your final _package.json_ will look like this:

![Final package.json](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2z5go35uges3yglvf1zl.png)

Your final folder structure will look like this:

![Final Folder Structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ks15qanpnk4pxgn28wa.png)

## Conclusion

By following this guide, you now have a production-ready React application setup with Webpack, TypeScript, ESLint and Prettier. This setup provides a solid foundation for building scalable and maintainable React applications with best practices in place.
Remember to keep your dependencies up-to-date and continue learning about these tools to optimize your development workflow further. 
Happy coding!❤️

> If you found this article useful, please share it with your friends and colleagues!

Read more articles on Dev.To ➡️ [Shivam Pawar](https://dev.to/shivampawar)

Follow me on ⤵️
🌐 [LinkedIn](https://www.linkedin.com/in/shivam-prakash-pawar/)
🌐 [Github](https://github.com/shivam-pawar)