Typescript---webpack和Babel的使用 03

webpack

  • 通常情况下,实际开发中我们都需要使用构建工具对代码进行打包,TS同样也可以结合构建工具一起使用,下边以webpack为例介绍一下如何结合构建工具使用TS。

  • 步骤:

    1. 初始化项目

      • 进入项目根目录,执行命令 npm init -y
        • 主要作用:创建package.json文件
    2. 下载构建工具

      • npm i -D webpack webpack-cli webpack-dev-server typescript ts-loader clean-webpack-plugin
        • 共安装了7个包
          • webpack
            • 构建工具webpack
          • webpack-cli
            • webpack的命令行工具
          • webpack-dev-server
            • webpack的开发服务器
          • typescript
            • ts编译器
          • ts-loader
            • ts加载器,用于在webpack中编译ts文件
          • html-webpack-plugin
            • webpack中html插件,用来自动创建html文件
          • clean-webpack-plugin
            • webpack中的清除插件,每次构建都会先清除目录
    3. 根目录下创建webpack的配置文件webpack.config.js

      • const path = require("path");
        const HtmlWebpackPlugin = require("html-webpack-plugin");
        const {
                  CleanWebpackPlugin } = require("clean-webpack-plugin");
        
        module.exports = {
                 
            optimization:{
                 
                minimize: false // 关闭代码压缩,可选
            },
        
            entry: "./src/index.ts",
            
            devtool: "inline-source-map",
            
            devServer: {
                 
                contentBase: './dist'
            },
        
            output: {
                 
                path: path.resolve(__dirname, "dist"),
                filename: "bundle.js",
                environment: {
                 
                    arrowFunction: false // 关闭webpack的箭头函数,可选
                }
            },
        
            resolve: {
                 
                extensions: [".ts", ".js"]
            },
            
            module: {
                 
                rules: [
                    {
                 
                        test: /\.ts$/,
                        use: {
                 
                           loader: "ts-loader"     
                        },
                        exclude: /node_modules/
                    }
                ]
            },
        
            plugins: [
                new CleanWebpackPlugin(),
                new HtmlWebpackPlugin({
                 
                    title:'TS测试'
                }),
            ]
        
        }
        
    4. 根目录下创建tsconfig.json,配置可以根据自己需要

      • {
                 
            "compilerOptions": {
                 
                "target": "ES2015",
                "module": "ES2015",
                "strict": true
            }
        }
        
    5. 修改package.json添加如下配置

      • {
                 
          ......
          "scripts": {
                 
            "test": "echo \"Error: no test specified\" && exit 1",
            "build": "webpack",
            "start": "webpack serve --open chrome.exe"
          },
          ......
        }
        
    6. 在src下创建ts文件,并在并命令行执行npm run build对代码进行编译,或者执行npm start来启动开发服务器

5、Babel

  • 经过一系列的配置,使得TS和webpack已经结合到了一起,除了webpack,开发中还经常需要结合babel来对代码进行转换以使其可以兼容到更多的浏览器,在上述步骤的基础上,通过以下步骤再将babel引入到项目中。

    1. 安装依赖包:

      • npm i -D @babel/core @babel/preset-env babel-loader core-js
      • 共安装了4个包,分别是:
        • @babel/core
          • babel的核心工具
        • @babel/preset-env
          • babel的预定义环境
        • @babel-loader
          • babel在webpack中的加载器
        • core-js
          • core-js用来使老版本的浏览器支持新版ES语法
    2. 修改webpack.config.js配置文件

      • ......
        module: {
                 
            rules: [
                {
                 
                    test: /\.ts$/,
                    use: [
                        {
                 
                            loader: "babel-loader",
                            options:{
                 
                                presets: [
                                    [
                                        "@babel/preset-env",
                                        {
                 
                                            "targets":{
                 
                                                "chrome": "57",
                                                "ie": "11"
                                            },
                                            "corejs":"3",
                                            "useBuiltIns": "usage"
                                        }
                                    ]
                                ]
                            }
                        },
                        {
                 
                            loader: "ts-loader",
        
                        }
                    ],
                    exclude: /node_modules/
                }
            ]
        }
        ......
        
      • 如此一来,使用ts编译后的文件将会再次被babel处理,使得代码可以在大部分浏览器中直接使用,可以在配置选项的targets中指定要兼容的浏览器版本。

测试:
在这里插入图片描述

webpack.config.js

// 引入一个包
const path = require('path');
// 引入html插件
const HTMLWebpackPlugin = require('html-webpack-plugin');
// 引入clean插件
const {
    CleanWebpackPlugin } = require('clean-webpack-plugin');

// webpack中的所有的配置信息都应该写在module.exports中
module.exports = {
   

    // 指定入口文件
    entry: "./src/index.ts",

    // 指定打包文件所在目录
    output: {
   
        // 指定打包文件的目录
        path: path.resolve(__dirname, 'dist'),
        // 打包后文件的文件
        filename: "bundle.js",

        // 告诉webpack不使用箭头
        environment:{
   
            arrowFunction: false
        }
    },

    // 指定webpack打包时要使用模块
    module: {
   
        // 指定要加载的规则
        rules: [
            {
   
                // test指定的是规则生效的文件
                test: /\.ts$/,
                // 要使用的loader
                use: [
                     // 配置babel
                     {
   
                         // 指定加载器
                         loader:"babel-loader",
                         // 设置babel
                         options: {
   
                             // 设置预定义的环境
                             presets:[
                                 [
                                     // 指定环境的插件
                                     "@babel/preset-env",
                                     // 配置信息
                                     {
   
                                         // 要兼容的目标浏览器
                                         targets:{
   
                                             "chrome":"58",
                                             "ie":"11"
                                         },
                                         // 指定corejs的版本
                                         "corejs":"3",
                                         // 使用corejs的方式 "usage" 表示按需加载
                                         "useBuiltIns":"usage"
                                     }
                                 ]
                             ]
                         }
                     },
                    'ts-loader'
                ],
                // 要排除的文件
                exclude: /node-modules/
            }
        ]
    },

    // 配置Webpack插件
    plugins: [
        new CleanWebpackPlugin(),
        new HTMLWebpackPlugin({
   
            // title: "这是一个自定义的title"
            template: "./src/index.html"
        }),
    ],

    // 用来设置引用模块
    resolve: {
   
        extensions: ['.ts', '.js']
    }

};

package.json

{
   
  "name": "part3",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
   
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "start": "webpack serve --open chrome.exe"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
   
    "@babel/core": "^7.12.9",
    "@babel/preset-env": "^7.12.7",
    "babel-loader": "^8.2.2",
    "clean-webpack-plugin": "^3.0.0",
    "core-js": "^3.8.0",
    "html-webpack-plugin": "^4.5.0",
    "ts-loader": "^8.0.11",
    "typescript": "^4.1.2",
    "webpack": "^5.6.0",
    "webpack-cli": "^4.2.0",
    "webpack-dev-server": "^3.11.0"
  }
}

tsconfig.json

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

相关推荐

  1. webpack使用

    2024-01-05 13:30:04       38 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-05 13:30:04       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-05 13:30:04       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-05 13:30:04       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-05 13:30:04       18 阅读

热门阅读

  1. HarmonyOS@Builder装饰器

    2024-01-05 13:30:04       48 阅读
  2. 面试算法91:粉刷房子

    2024-01-05 13:30:04       39 阅读
  3. 复试 || 就业day09(2024.01.04)算法篇

    2024-01-05 13:30:04       39 阅读
  4. 测试找bug是个技术活

    2024-01-05 13:30:04       40 阅读