SoFunction
Updated on 2025-03-10

Teach you how to compile TypeScript code using webpack package

TypeScript Packaging

webpack integration

Usually, in actual development, we need to use build tools to package the code;

TS can also be used in combination with build tools. Let’s take webpack as an example to introduce how to use TS in combination with build tools;

The steps are as follows:

Initialize the project

Enter the project root directory and execute the commandnpm init -y, create a file

Download the build tool

The command is as follows:

npm i -D webpack webpack-cli webpack-dev-server typescript ts-loader clean-webpack-plugin

A total of 7 packages were installed:

  • webpack: build tool webpack
  • webpack-cli: webpack command line tool
  • webpack-dev-server: webpack development server
  • typescript:ts compiler
  • ts-loader: ts loader, used to compile ts files in webpack
  • html-webpack-plugin: html plugin in webpack, used to automatically create html files
  • clean-webpack-plugin: Clear plugin in webpack, the directory will be cleared first every time you build it

Configurationwebpack

Create webpack configuration file in the root directory

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

 = {
   optimization:{
       minimize: false // Turn off code compression, optional   },

   entry: "./src/",

   devtool: "inline-source-map",

   devServer: {
       contentBase: './dist'
   },

   output: {
       path: (__dirname, "dist"),
       filename: "",
       environment: {
           arrowFunction: false // Close webpack's arrow function, optional       }
   },

   resolve: {
       extensions: [".ts", ".js"]
   },

   module: {
       rules: [
           {
               test: /\.ts$/,
               use: {
                   loader: "ts-loader"     
               },
               exclude: /node_modules/
           }
       ]
   },

   plugins: [
       new CleanWebpackPlugin(),
       new HtmlWebpackPlugin({
           title:'TS Test'
       }),
   ]
}

Configure TS compilation options

Created in the root directory, and the configuration can be based on your needs

{
   "compilerOptions": {
       "target": "ES2015",
       "module": "ES2015",
       "strict": true
   }
}

Modify configuration

Modify and add the following configuration

{
   ...
   "scripts": {
       "test": "echo \"Error: no test specified\" && exit 1",
       "build": "webpack",
       "start": "webpack serve --open "
   },
   ...
}

Project usage

Create ts file under src and execute on the command linenpm run buildCompile the code;

Or executenpm startto start the development server;

Babel

In addition to webpack, it is often necessary to combine babel to convert the code during development;

In order to make it compatible with more browsers, based on the above steps, use the following steps to introduce babel into the project;

Although TS also supports code conversion at compile time, it only supports simple code conversion;

For ES6 features such as Promise, TS cannot be converted directly, and babel must be used for conversion at this time;

Install dependency package:

npm i -D @babel/core @babel/preset-env babel-loader core-js

A total of 4 packages were installed, namely:

  • @babel/core: Babel's core tool
  • @babel/preset-env: Babel's predefined environment
  • @babel-loader: babel loader in webpack
  • core-js: core-js is used to make old browsers support new ES syntax

Modify the configuration file

module: {
    rules: [
        {
            test: /\.ts$/,
            use: [
                {
                    loader: "babel-loader",
                    options:{
                        presets: [
                            [
                                "@babel/preset-env",
                                {
                                    "targets":{
                                        "chrome": "58",
                                        "ie": "11"
                                    },
                                    "corejs":"3",
                                    "useBuiltIns": "usage"
                                }
                            ]
                        ]
                    }
                },
                {
                    loader: "ts-loader",
                }
            ],
            exclude: /node_modules/
        }
    ]
}

In this way, the file compiled with ts will be processed by babel again;

Make the code directly used in most browsers;

You can also specify the browser version to be compatible in the targets of the configuration options;

This is the article about using webpack to package and compile TypeScript code. For more related webpack to package and compile TypeScript content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!