Use webpack to package typescript (.ts); babel.js is compatible with lower version browsers

1. npm init -yInitialize

2. Install webpack related dependencies

  1. cnpm i webpack webpack-cli -D;

3. The most basic configuration of webpack

3.1 Create a webpack configuration file in the project root directory webpack.config.js, and perform the following basic configurations;

const path = require("path");

module.exports = {
    
    
  // 入口文件
  entry: "./src/index.js",

  // 输出路径
  output: {
    
    
    filename: "bundle.js", // 输出文件名称
    path: path.resolve(__dirname, "./dist"), // 输出路径
  },
};

3.2 Edit package.jsonthe file and add packaging commands;

  • scriptsAdded in "build": "webpack", the final result is as follows
"scripts": {
    
    
  "test": "echo \"Error: no test specified\" && exit 1",
  "build": "webpack"
}
  • npx webpackOr execute directly npxto package and compile;

3.3 npm run buildRun the packaging tool

  • According to the configuration of the entry file in webpack.config.jsthe configuration file, create an entry file with a matching path.

4. Configure the typescript packaging environment

4.1 cnpm i typescript ts-loader -D

4.2 Compilation configuration configured webpack.config.jsintypescript

const path = require("path");

module.exports = {
    
    
  // 入口文件
  entry: "./src/index.ts", // ************ --- 这里修改为 ts 文件

  // 输出路径
  output: {
    
    
    filename: "bundle.js", // 输出文件名称
    path: path.resolve(__dirname, "./dist"), // 输出路径
  },

  module: {
    
    
    rules: [
      {
    
    
        // 按规则匹配需要进行加载的文件
        test: /\.ts$/,
        // 使用加载器的名称 
        use: 'ts-loader',
        // 排除不需要加载的文件
        exclude: /node_modules/,
      }
    ]
  },
}

4.3 tsconfig.jsonts compilation configuration file

  • Create a ts compilation configuration file in the root directory tsconfig.json, create it directly, and an empty file can also take effect;
  • Or use tsc --initto generate a configuration file, which contains some default configurations that need to be modified as needed;

Run npm run buildto compile ts;

5. Babel is compatible with lower version browsers

5.1 cnpm i @babel/core @babel/preset-env babel-loader core-js -D;

5.2 Modify the configuration file webpack.config.js;

module.exports = {
    
    
  output: {
    
    
    // 1. *** --- 设置webpack不使用箭头函数 --- ***/
    environment: {
    
    
      arrowFunction: false,
    },
  },

  module: {
    
    
    rules: [
      {
    
    
        // 按规则匹配需要进行加载的文件
        test: /\.ts$/,
        // 使用加载器的名称 
        // 加载器运行顺序, 由后往前;(此处: 先通过ts-loader将ts编译为js, 然后使用babel-loader进行兼容性处理)
        use: [

          // 2. *** --- babel最重要的一坨配置 --- *** //
          {
    
    
            loader: 'babel-loader',
            options:{
    
    
              presets: [
                [
                  "@babel/preset-env",
                  {
    
    
                    // 配置需要兼容的浏览器
                    targets: {
    
    
                      "chrome": "79",
                      "ie": "11",
                    },
                    // 指定core-js版本
                    "corejs": "3",
                    // 设置core-js的使用方式
                    "useBuiltIns": "usage", // usage: 按需加载
                  }
                ]
              ],
            },
          },
          // *** --- / 2. babel最重要的一坨配置 --- *** //

          'ts-loader',
        ],
        // 排除不需要加载的文件
        exclude: /node_modules/,
      }
    ]
  },
}

6. Automatically delete existing historical dist files when compiling

6.1 cnpm i clean-webpack-plugin -D: Install third-party plug-ins;

6.2 Modify the configuration file

const {
    
     CleanWebpackPlugin } = require("clean-webpack-plugin")

module.exports = {
    
    
  // ... 其余配置
  plugins: [
    new CleanWebpackPlugin(),
  ],
}

7. Specify the html template

  • cnpm i html-webpack-plugin -D: install dependencies;
  • Modify the configuration file
const {
    
     CleanWebpackPlugin } = require("clean-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    
    
  // ... 其余配置
  plugins: [
    new CleanWebpackPlugin(),
    // 指定模板文件
    // 插件会自动将编译出来的入口文件(./dist/bundle.js)引入到 html 文件中;
    // 如果html没有需要特殊配置,可直接省略指定模板文件, 如下:
    // new HtmlWebpackPlugin()
    new HtmlWebpackPlugin({
    
    
      template: "./index.html", 
    }),
  ],
}

8. Hot compilation & mode compilation mode

Dynamically monitor ts file changes and automatically compile;

  • cnpm i webpack-dev-server -D
  • Configure debug commands
"scripts": {
    
    
  "test": "echo \"Error: no test specified\" && exit 1",
  "build": "webpack",
  // --open: 自动打开默认浏览器
  // --mode=development: 指定调试模式为开发(development)模式
  // --mode=production: 指定调试模式为生产(production)模式
  "dev": "webpack serve --open --mode=development",
  "prod": "webpack serve --open --mode=production"
}
  • View the current debug mode
console.log(process.env.NODE_ENV);
  • cnpm run dev: enable debugging

final state

Install all dependencies

cnpm i -D webpack webpack-cli typescript ts-loader @babel/core @babel/preset-env babel-loader core-js clean-webpack-plugin html-webpack-plugin webpack-dev-server

webpack.config.jsConfiguration file final state

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

module.exports = {
    
    
  // 入口文件
  entry: "./src/index.ts",

  // 输出路径
  output: {
    
    
    filename: "bundle.js", // 输出文件名称
    path: path.resolve(__dirname, "./dist"), // 输出路径
    // 设置webpack不使用箭头函数
    environment: {
    
    
      arrowFunction: false,
    },
  },

  module: {
    
    
    rules: [
      {
    
    
        // 按规则匹配需要进行加载的文件
        test: /\.ts$/,
        // 使用加载器的名称 
        // 加载器运行顺序, 由后往前;(此处: 先通过ts-loader将ts编译为js, 然后使用babel-loader进行兼容性处理)
        use: [

          // *** --- babel最重要的一坨配置 --- *** //
          {
    
    
            loader: 'babel-loader',
            options: {
    
    
              presets: [
                [
                  "@babel/preset-env",
                  {
    
    
                    // 配置需要兼容的浏览器
                    targets: {
    
    
                      "chrome": "79",
                      "ie": "11",
                    },
                    // 指定core-js版本
                    "corejs": "3",
                    // 设置core-js的使用方式
                    "useBuiltIns": "usage", // usage: 按需加载
                  }
                ]
              ],
            },
          },
          // *** --- / babel最重要的一坨配置 --- *** //
          'ts-loader',
        ],
        // 排除不需要加载的文件
        exclude: /node_modules/,
      }
    ]
  },

  plugins: [
    new CleanWebpackPlugin(),
    // 指定模板文件
    // 插件会自动将编译出来的入口文件(./dist/bundle.js)引入到 html 文件中;
    // 如果html没有需要特殊配置,可直接省略指定模板文件, 如下:
    // new HtmlWebpackPlugin()
    new HtmlWebpackPlugin({
    
    
      template: "./index.html",
    }),
  ],
}

package.jsonfile final state

{
    
    
  "name": "typescript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    
    
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --mode=production",
    "dev": "webpack serve --open --mode=development",
    "prod": "webpack serve --open --mode=production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    
    
    "@babel/core": "^7.19.6",
    "@babel/preset-env": "^7.19.4",
    "babel-loader": "^8.2.5",
    "clean-webpack-plugin": "^4.0.0",
    "core-js": "^3.25.5",
    "html-webpack-plugin": "^5.5.0",
    "ts-loader": "^9.4.1",
    "typescript": "^4.8.4",
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0",
    "webpack-dev-server": "^4.11.1"
  }
}

tsconfig.jsonfile final state

  • This file is tsc --initautomatically and will not be displayed;

Directory Structure

insert image description here

So far: .tsthe webpack packaging function of the file has been realized

Guess you like

Origin blog.csdn.net/cc_King/article/details/127438053