Webpack Configuration (part-4) – Setup Typescript

Install this dependencies

$ npm install --save-dev typescript ts-loader
JavaScript

Add the scripts in package.json

    "scripts": {
      "build": "webpack",
      "start": "webpack serve",
    }
JavaScript

Init a Tsconfig file :

tsc --init
JavaScript
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node",
    "outDir": "dist",
    "sourceMap": true
  }
}
JavaScript

These options instruct the TypeScript compiler to:

  • Target ES5 syntax for better browser compatibility
  • Use CommonJS modules
  • Enable strict type checking
  • Use Node-style module resolution
  • Output the compiled JavaScript files to the dist directory
  • Generate source maps for easier debugging

Update the webpack.config.js like this :

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

const config = {
  mode: "development", // Defines the mode to pass to webpack.
  entry: "./src/index.ts", // The entry point(s) of your application e.g. ./src/main.js.
  output: {
    // Output location of the file generated by webpack e.g. ./dist/.
    path: path.resolve(__dirname, "dist"),
    filename: "[name].[contenthash].js",
  },
  devtool: "source-map",
  devServer: {
    historyApiFallback: true,
    static: {
      directory: path.join(__dirname, "public"), // Directory for static contents.
    },
    compress: true, //  Enables gzip compression for everything served.
    port: 9000, // Allows to specify a port to use.
    hot: true, //  Enables Hot Module Replacement.
    open: true, //  Allows to configure dev server to open the browser(s) and page(s) after server had been started (set it to true to open your default browser).
    liveReload: true, // Enables reload/refresh the page(s) when file changes are detected (enabled by default).
    client: {
      progress: true, // Prints compilation progress in percentage in the browser.
    },
  },
  plugins: [
    <strong>new</strong> HtmlWebpackPlugin({
      title: "Output Management",
      template: "./public/index.html", // Specify the path to your existing index.html
      filename: "index.html",
    }),
  ],
  optimization: {
    runtimeChunk: "single",
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: "vendors",
          chunks: "all",
        },
      },
    },
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env"],
          },
        },
      },
      {
        test: /\.tsx?$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"],
  },
};

<em>module</em>.<em>exports</em> = config;
JavaScript

We have updated the module rules to include the ts-loader and also updated the resolve extentions. We added the devtools to source-map.

Update the index.js to index.ts and also update the entry point in webpack.config.js

// entry index.js
console.log("hello world");

function greet(<em>name</em>: <em>string</em>): <em>string</em> {
  return `Hello, ${name}!`;
}

const user = "TypeScript Developer";

console.log(greet(user));
JavaScript

Cool !

Now the index.html should be the same like previous

<!DOCTYPE html>
 <html lang="en-US">
  <head>
        <title> TS Webpack Boilerplate </title>

        <meta name="charset" content="UTF-8" />
        <meta name="description" content="TS Webpack Boilerplate App" />
        <meta name="keywords" content="javascript, typescript, webpack, ts-boilerplate, webpack-boilerplate" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />

        <link rel="stylesheet" type="text/css" href="./styles/global.css" />
    </head>
    <body>
        <header> 
            <div id="logo-container">
                <h1> TS WEBPACK BOILERPLATE</h1>
            </div>
            <div id="nav-container">
                <nav aria-label="Navigation">
                     <ul role="menu" aria-label="menu">
                        <li role="menuitem" aria-label="Home">
                            <a href="/"> Home </a>
                        </li>
                        <li role="menuitem" aria-label="About">
                            <a href="/about"> About </a>
                        </li>
                        <li role="menuitem" aria-label="Contact">
                            <a href="/contact"> Contact </a>
                        </li>
                    </ul>
                </nav>
            </div>
           
        </header>

        <main>
            <h1 id="main-heading"> This is a setup built on Webpack, Typescript, SAAS</h1>

            <div id="app"></div>
        </main>

        <footer>
            <p>© 2023</p>
        </footer>
    </body>
</html>
JavaScript

Running the app,

First we need to tell webpack to bundle our application, run the following command

$ npm run build
JavaScript

Then to start the app :

$ npm run start
JavaScript

The app should be up at http://localhost:9000

Great ! It works. In the next part, we will see how to setup more configurations like SaaS, eslint etc. with Webpack.

You can refer to the following Github Commit for reference

https://github.com/sujaykundu777/ts-webpack-boilerplate/commit/8ea74208e402025a83abb68c1e3f6e3a9e677bad

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *