Using Webpack to build React Application

webpack.config.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require("webpack")
const port = process.env.PORT || 3000;
module.exports = {
    mode:  "development",
    devtool:"source-map",
    entry:{
        main: "./src/index.tsx",
    },
    output:{
        filename:'[name].js',
        path:__dirname +"/dist",
    },
    resolve:{
        alias: {
          "react-dom": "@hot-loader/react-dom",
        },
        extensions:[".ts",".tsx",".js",".scss",".css"],
        modules: [ "node_modules"]
    },
    //  add the additional function to webpack
    plugins:[
      // enable hot reload
      new webpack.HotModuleReplacementPlugin() ,
      // separate css file from js file when building
      new MiniCssExtractPlugin({filename:"[name].css"}),
      // generate html file with output script 
      new HtmlWebpackPlugin({
        template: "public/index.html",
        favicon: "public/favicon.ico"
      })
    ],
    //  the default only handle js file, so need to add loader to process the 
    //  dependency
    module:{
        rules:[
          //  compile tsx to js and then to browser compatible language 
          //  through babel
          {
            test: /\.tsx?$/,
            use: ["babel-loader" , {
              loader: "ts-loader",
              options: {
                configFile: "tsconfig.json",
              },
            }],
            exclude: /node_modules/,
          },
          //  compile scss to css and then build to separate css file
          {
            test: /\.scss$/i,
            use: [
              MiniCssExtractPlugin.loader,
              {
                loader: "css-loader",
                options: {
                  modules: true,
                },
              },
              "sass-loader"
            ],
          }
        ]
    },
    // maintain dev server for local env
    devServer:{
      host: "localhost",
      port : port,
      historyApiFallback: true,
      open: true,
      hot:true
    }
}

Last updated

Was this helpful?