用 Webpack 实现 一个 TypeScript 代码执行器

138 阅读2分钟

webpack ts runner

github链接:sworddut/webpack-ts-runner

目标

我们要用 Webpack 打包一个 TypeScript 代码执行器,最终可以通过 npm run build 运行 index.ts

🛠 第 1 步:初始化项目

首先,我们需要创建一个新的 Node.js 项目并安装 Webpack。

1.1. 创建项目文件夹

mkdir webpack-ts-runner
cd webpack-ts-runner

1.2. 初始化 package.json

npm init -y

这会生成一个 package.json,用来管理依赖。

🛠 第 2 步:安装 Webpack

Webpack 是一个模块打包工具,核心包括:

  • webpack:主程序
  • webpack-cli:提供 Webpack 的命令行工具

安装 Webpack:

npm install webpack webpack-cli --save-devbash

测试 Webpack 是否安装成功:

npx webpack -v

如果能看到 Webpack 版本号,说明安装成功。

🛠 第 3 步:创建源代码

我们先写一个简单的 TypeScript 代码:

3.1. 创建 src/index.ts

webpack-ts-runner 目录下,新建 src/index.ts

export function add(a: number, b: number): number {
  return a + b;
}
​
console.log("Result:", add(2, 3));

🛠 第 4 步:配置 TypeScript

Webpack 不能直接处理 TypeScript,我们需要安装 ts-loadertypescript

安装 TypeScript 及 ts-loader:

npm install typescript ts-loader --save-dev

4.1. 创建 tsconfig.json

新建 tsconfig.json,告诉 TypeScript 如何编译:

{
  "compilerOptions": {
    "outDir": "./dist",
    "module": "CommonJS",
    "target": "ES6",
    "strict": true
  }
}

🛠 第 5 步:配置 Webpack

新建 webpack.config.js,用于告诉 Webpack 如何打包项目。

5.1. 创建 webpack.config.js

在项目根目录下创建 webpack.config.js

const path = require('path')
​
modules.exports = {
    entry:"./scr/index.ts",
    mode: "development", 
    target: "node", // 目标环境是 Node.js
    output:{
        filename:"index.js",
        path:path.resolve(__dirname,"dist")
    },
    resolve:{
        extensions:[".ts",".js"]
    },
    modules:{
        rules:[
            {
                test:/.ts$/,
                use:"ts-loader",
                exclude:/node_module/
            }
        ]
    }
    
}

配置解析

  • entry: 入口文件是 src/index.ts
  • mode: 设为 "development",方便调试。
  • target: 设为 "node",因为我们要在 Node.js 运行。
  • output: Webpack 会把编译后的文件放到 dist/index.js
  • resolve.extensions: 允许 Webpack 解析 .ts.js 文件。
  • module.rules: 告诉 Webpack 用 ts-loader 处理 .ts 文件。

🛠 第 6 步:测试打包

现在,我们来尝试用 Webpack 打包 TypeScript 代码。

package.json 里添加 Webpack 构建命令:

"scripts": {
  "build": "webpack"
}

运行:

npm run build

如果成功,你会看到 dist/index.js 生成,并且 console.log 代码还在。

🛠 第 7 步:实现持续监听

下面,实现webpack监听index.ts的保存自动重新打包编译

7.1. 新建 RunAfterCompilePlugin.js

const { exec } = require("child_process");
​
class RunAfterCompilePlugin:{
    apply(compiler){
        compiler.hooks.done.tap("RunAfterCompilePlugin",()=>{
            console.log("Build complete. Running output...");
            exce("node dist/index.js",(error,stdout,stderr)=>{
                if(error){
                    console.error(`Execution error: ${error}`);
                    return;
                }
                console.log(stdout);
                console.error(stderr);
            })
        })
    }
}
​
module.exports = RunAfterCompilePlugin;

7.2. 修改 webpack.config.js

导入并使用插件:

const path = require("path");
const RunAfterCompilePlugin = require("./RunAfterCompilePlugin");
​
module.exports = {
  entry: "./src/index.ts",
  mode: "development",
  target: "node",
  output: {
    filename: "index.js",
    path: path.resolve(__dirname, "dist"),
  },
  resolve: {
    extensions: [".ts", ".js"],
  },
  module: {
    rules: [
      {
        test: /.ts$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
    ],
  },
  watch:true, //开启监听模式
  plugins: [new RunAfterCompilePlugin()],//导入插件
};

开启监听模式,webpack在打包成功后会持续监听文件修改,不会关闭。修改时执行了RunAfterCompilePlugin的插件输出,实现持续监听的效果

🛠 第 8 步:处理异常

8.1. 修改 RunAfterCompilePlugin.js

const { exec } = require("child_process");
​
class RunAfterCompilePlugin {
  apply(compiler) {
    compiler.hooks.done.tap("RunAfterCompilePlugin", (stats) => {
      console.log("\n✅ Build complete. Running output...\n");
      exec("node dist/index.js", (error, stdout, stderr) => {
        if (error) {
          console.error(`Execution error: ${error}`);
          return;
        }
        if (stats.hasErrors()) {
          console.error("\n🚨 Build failed! Not executing output.\n");
          return;
        }
        console.log("执行成功:",stdout);
      });
    });
  }
}
​
module.exports = RunAfterCompilePlugin;

总结

Webpack 配置

  • entry: 指定 index.ts 作为入口文件。
  • output: 编译后的文件放到 dist/index.js
  • module.rules: 用 ts-loader 处理 TypeScript 文件。
  • plugins: 添加 RunAfterCompilePlugin,在编译完成后运行代码。
  • watch:设置为true,让webpack在打包成功后仍可以持续监听文件修改。

Webpack 插件

  • RunAfterCompilePlugin 使用 Webpack 的 done 钩子,在构建完成后自动执行 dist/index.js

使用方式

  • npm run build → 打包 TypeScript 代码。