This is the 18th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

If you feel helpful, please click 👍 to encourage you

Webpack integration

Often, in real development, we need to use build tools to package code;

TS can also be used with the build tool. The following uses Webpack as an example to introduce how to use TS with the build tool.

1. Initialize the project

Go to the root directory of the project and run NPM init -y to create the package.json file

2. Download the build tool

npm i -D webpack webpack-cli webpack-dev-server typescript ts-loader clean-webpack-plugin html-webpack-plugin
Copy the code

A total of 7 packages were installed:

  • Webpack: Build tool Webpack
  • Webpack-cli: Command line tool for Webpack
  • Webpack-dev-server: development server for Webpack
  • Typescript: TS compiler
  • Ts-loader: TS loader used to compile TS files in webpack
  • Html-webpack-plugin: HTML plug-in in webpack, used to automatically create HTML files
  • Clean-webpack-plugin: A clean plug-in in webpack that cleans the directory first with each build

3. The configuration webpack

The configuration file webpack.config.js that creates webpack in the root directory

// Introduce a module that handles the path
const path = require('path');
// Introduce a plug-in that automatically generates HTML
const HTMLWebpackPlugin = require('html-webpack-plugin');
// Introduce a plug-in that clears the dist directory before each package
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

// All webpack configuration information is written in modules.exports
module.exports = {
  
   optimization: {minimize: false // Turn off code compression, optional
   },

  // Specify the entry file
  entry: './src/index.ts'.// Specify the directory where the package file resides
  output: {
    // Specify a directory for the packaged files
    path: path.resolve(__dirname, 'dist'),
    // The name of the packaged file
    filename: 'bundle.js'.// Disable arrow function optional
    environment: {
      arrowFunction: false,}},// Specify the module to use when webpack is packaged
  module: {
    // Specify the rules to load
    rules: [{// test specifies the file in which the rule takes effect
        test: /.ts$/.// The loader to use handles the TS file
        use: [
          'ts-loader',].// Files to be excluded
        exclude: /node_modules/,}]},// Configure the WebPack plug-in
  plugins: [
    // Automatically generate HTML
    new HTMLWebpackPlugin({
      // Customize title
      title: 'Custom title'.// This file is used as the template for the packaged HTML of the configuration template
      template: './src/index.html',}).// Automatically delete files in dist
    new CleanWebpackPlugin(),
  ],

  // Sets which files can be imported as modules
  resolve: {
    extensions: ['.ts'.'.js'],}};Copy the code

4. Configure TS compilation options

Tsconfig. json is created in the root directory and can be configured according to your needs

{
   "compilerOptions": {
     	 // To specify the ES version to which TS is compiled
       "target": "ES2015".// Used to specify which modular solution to use
       "module": "ES2015".// All strictly checked master switches
       "strict": true}}Copy the code

5. Modify package.json configuration

"scripts": {
  // Package through webpack
  "build": "webpack".// Start the Web server with Webpack and turn on support for hot updates using Google Chrome
  "start": "webpack serve --open chrome.exe"
},
Copy the code

6. Project use

Create the ts file under SRC and run the NPM run build command line to compile the code.

Or run NPM start to start the development server;

Babel

  • In addition to WebPack, Babel is often used in development to transform code to make it compatible with more browsers
  • Although TS does support code conversion at compile time, it only supports simple code conversion. For ES6 features such as Promise, TS cannot convert directly.

1. Install dependency packages:

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

A total of 4 packages are installed, which are:

  • Babel /core: The core tool of Babel
  • @babel/preset-env: Preset environment of Babel
  • @babel-loader: loader for Babel in webpack
  • Core-js: Core-js is used to enable older browsers to support the new ES syntax

2. Modify the webpack.config.js configuration file

 / / configuration Babel
{
  // Specify the loader
  loader: 'babel-loader'./ / set the Babel
    options: {
      // Set the predefined environment
      presets: [[// Specify the environment plug-in
          '@babel/preset-env'.// Configuration information
          {
            // Specify the browser version
            targets: {
              chrome: '58'.ie: '11',},// Specify the corejs version
            corejs: '3'.// Use corejs to represent usage on demand
            useBuiltIns: 'usage',},],],},},Copy the code

This way, files compiled using TS will be processed by Babel again, making the code usable in most browsers.