Teach you how to use webpack to package and compile TypeScript code

Teach you how to use webpack to package and compile TypeScript code

TypeScript Bundling

webpack integration

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

TS can also be used in conjunction with build tools. The following uses webpack as an example to introduce how to use TS in conjunction with build tools.

Here are the steps:

Initialize the project

Enter the project root directory and execute the command npm init -y to create a package.json file

Download the build tools

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: command line tool for webpack
  • 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: A cleanup plugin in webpack that will clean the directory before each build

Configure webpack

Create the webpack configuration file webpack.config.js in the root directory:

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

module.exports = {
   optimization:
       minimize: false // turn off code compression, optional},

   entry: "./src/index.ts",

   devtool: "inline-source-map",

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

   output: {
       path: path.resolve(__dirname, "dist"),
       filename: "bundle.js",
       environment:
           arrowFunction: false // Turn off 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

Create tsconfig.json in the root directory and configure it according to your needs

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

Modify package.json configuration

Modify package.json and add the following configuration

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

Project Usage

Create a ts file under src and execute npm run build in the command line to compile the code;

Or execute npm start to start the development server;

Babel

In addition to webpack, babel is often needed to convert code during development;

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

Although TS also supports code conversion during compilation, it only supports simple code conversion;

For ES6 features such as Promise, TS cannot be converted directly, so babel is needed for conversion;

Install dependency packages:

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 tools
  • @babel/preset-env: Babel's predefined environment
  • @babel-loader: babel loader in webpack
  • core-js: core-js is used to enable older browsers to support the new ES syntax

Modify the webpack.config.js 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 files compiled with ts will be processed by babel again;

Make the code directly usable in most browsers;

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

This is the end of this article about using webpack to package and compile TypeScript code. For more relevant webpack packaging and compiling TypeScript content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of using TypeScript for web application development
  • Websocket4.0+typescript method to implement hot update
  • React+TypeScript+webpack4 multi-entry configuration detailed explanation
  • Creating a simple web application with TypeScript

<<:  Detailed explanation of Zabbix installation and deployment practices

>>:  MySQL: Data Integrity

Recommend

A brief introduction to React

Table of contents 1. CDN introduction 1.1 react (...

What is the file mysql-bin.000001 in mysql? Can it be deleted?

After installing MySQL using ports, I found that ...

Solve the problem of OpenLayers 3 loading vector map source

1. Vector Map Vector graphics use straight lines ...

Using Docker+jenkins+python3 environment to build a super detailed tutorial

Preface: After the automation is written, it need...

How does JS understand data URLs?

Table of contents Overview Getting started with d...

Complete steps to install Anaconda3 in Ubuntu environment

Table of contents Introduction to Anaconda 1. Dow...

Vue+element ui realizes anchor positioning

This article example shares the specific code of ...

MySQL password is correct but cannot log in locally -1045

MySQL password is correct but cannot log in local...

A brief talk about the diff algorithm in Vue

Table of contents Overview Virtual Dom principle ...

VMware WorkStation 14 pro installation Ubuntu 17.04 tutorial

This article records the specific method of insta...

An article to help you learn more about JavaScript arrays

Table of contents 1. The role of array: 2. Defini...

Basic concepts and common methods of Map mapping in ECMAScript6

Table of contents What is a Mapping Difference be...