# @digitak/esrun 中文文档

规范地址：https://npmcn.com/package/%40digitak/esrun/

版本：3\.2\.26
npm 元数据更新时间：2023-12-14T15:28:06.178Z
中文译文更新时间：2026-11-12T08:24:10.907Z
软件包许可：ISC

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40digitak/esrun
原文对照：https://npmcn.com/package/%40digitak/esrun/?lang=original
项目主页：https://github.com/digital-loukoum/esrun#readme
源码仓库：https://github.com/digital-loukoum/esrun

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：32.9 kB，30 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=14\.0
- 运行依赖：3 个
- 首次发布：2021-01-14T19:11:59.842Z
- 最新版本发布：2023-12-14T15:28:05.989Z
- 近 30 天下载量：80228（2026-10-12 至 2026-11-10，npm 官方下载统计）
- 已发布版本数：70（近 12 个月 0 个）

## 中文简介

使用 Esbuilding 直接执行您的 Typescript 文件

## 安装

```sh
npm install @digitak/esrun
```

也可以使用：`pnpm add @digitak/esrun`、`yarn add @digitak/esrun`、`bun add @digitak/esrun`

## README

> **此软件包已移动到 [自动](https://www.npmjs.com/package/esrun)。这是一个遗留版本.**

# 自动

**自动** 是一个"工作出盒"库,用于执行Typescript (以及现代Javascript并带有装饰器等)而无需使用捆绑器. 用于快速演示或启动您用 Typescript 写的测试 .

这个图书馆是薄薄的包装 [兴建](https://github.com/evanw/esbuild) 它几乎立即编译出字典.

运行打字机的难度在于处理依赖性. 例如,您可能需要导入其他 Typescript 文件,但也需要导入用 Javascript 书写的库,并使用 CJS 或 ESM 格式. 所有这些使用案例都应予以考虑.

**自动** 能够处理所有烦人的东西 使事情如你所期望的那样运转.

## 使用量

### 全球安装

用您最喜欢的软件包管理器在全球安装库 :

```shell
npm i -g esrun
```

然后,您可以同样的方式执行任何 Typescript文件 :

```shell
esrun foo.ts
```

您可以像任何进程一样通过参数 :

```shell
esrun foo.ts --option=bar --verbose -S
```

所有文件的依赖性也会被捆绑和执行.

外部模块的依赖性不会被捆绑起来,这取决于 `node` 解决依赖关系的引擎.

### 当地安装

在本地安装您最喜欢的软件包管理器 .

```shell
npm i -D esrun
```

那你可以用在你的体内 `package.json` 脚本 :

```json
{
   "scripts": {
      "test": "esrun test"
   }
}
```

运行 `npm run test` 将运行以下列表中的第一个文件 :

-   `/test.ts`
-   `/test/index.ts`
-   `/test/test.ts`
-   `/test/main.ts`
-   `/test.js`
-   `/test/index.js`
-   `/test/test.js`
-   `/test/main.js`

### CLI 参数语法

有两种参数可以传递给esrun cli:

1.  **无效参数**,这将影响如何执行您的 Typescript 文件,
2.  财务报告和审定财务报表 **程序参数**,将转成 **进程.argv** 到要执行的文件.

**无效参数** 遵循与节点相同的语法惯例 :

-   它必须从双连字符" -"开始
-   之后是参数的名称
-   如果一个值是必需的,则使用一个等号"=",然后是该值,没有空格.

示例

```
esrun --tsconfig=/path/to/tsconfig.json myFileToExecute.ts
```

所有参数 **之后** 要执行的文件是 **程序参数** 并将通过 `process.argv`。 。 。 .

在这个例子中, `"foo"` 财务报告和审定财务报表 `"bar"` 将发送至 `myFileToExecute`数字 :

```
esrun myFileToExecute.ts foo bar
```

### 自定义 tsconfig.json

您可以通过自定义路径到您的 `tsconfig.json` 来自 CLI 的文件 :

```
esrun --tsconfig=/custom/path/to/tsconfig.json foo.ts
```

### 顶级等待

**埃斯伦** 与顶级等待兼容.

要启用顶级等待, 您需要设置选项 `"module": "esnext"` 在你的tsconfig.json中.

### 监视模式

您也可以执行 **自动** 在监视模式中.

在监视模式下,您的文件会在每次更新自身或其中一个依赖时自动被重新执行.

```shell
esrun --watch foo.ts
```

> 这个 `--watch` (或 `-w`) 选项必须放在要执行的文件路径之前. 如果您将其放置在文件路径后, 它将被传递为参数 `foo.ts` 换句话说.

这个功能在您进行测试驱动开发时非常有用. 你们可以跑 `esrun --watch test.ts` 并享受您在控制台上的 变化的现场输出.

您可能想要观看除代码文件之外的其他文件 。 例如,如果从配置文件中装入数据。 在这种情况下,您可以指定一个需要观看的光子(或光子列表):

```shell
esrun --watch=src/*.json foo.ts
```

随便 `json` 文档中 `src/`文件夹将重新触发运行 .

您可以使用由逗号分隔的多个缩写( 但无空格 ) :

```shell
esrun --watch=src/*.json,test/*.json foo.ts
```

#### 防止控制台清理

在监视模式下,每个文件更改都会触发控制台清除. 您可以禁用此行为 `--preserveConsole` 选项 :

```shell
esrun --watch --preserveConsole foo.ts
```

### 检查模式

您也可以执行 **自动** 检查模式.

在检查模式下运行时,您的代码会被连接到Webkit DevTools,以受益浏览器控制台的功率,而不是终端控制台.

首先,以检查模式运行您的程序 :

```shell
esrun --inspect foo.ts
```

然后打开 `about:inspect` 在一个 **颜色** 编号 : **勇敢点** 编号 : **边缘** 浏览器. 你应该看看你的节目在 _远程目标_ 节.

点击 `Open dedicated DevTools for Node` 并享受您的后端程序的浏览器控制台.

如果遇到麻烦,请读一下 [节点文档](https://nodejs.org/en/docs/guides/debugging-getting-started/)。 。 。 .

> 检查和监视模式尚未兼容 .

### Sudo 模式

您可以以 sudo 模式运行脚本 :

```
esrun --sudo myScript.ts
```

### 其他节点 cli 选项

`esrun` 使用 esbuilt 将 Typescript 转换为 Javascript, 然后由节点执行 .

您可以通过将选项名称前缀为"-node"来将自定义选项传递给节点 cli, 像这样:

```
esrun --node-max-old-space-size=4096 foo.ts
esrun --node-no-warnings foo.ts
```

### 导入 CJS 模块

如果导入 CJS 模块( 如 `typescript` 库本身),很可能需要设置 [eModule Interop 服务器](https://www.typescriptlang.org/tsconfig#esModuleInterop) 在您的旗帜 `tsconfig.json` 文件 :

```json
{
    "compilerOptions": {
        "esModuleInterop": true
    }
}
```

这将抑制 Typescript 编译器的导入错误, 并允许您写入 `import ts from "typescript"` 改为 `import * as ts from "typescript"` - 最新的语法不是标准的无害环境管理.

### 使用目录作为切入点

如果给定的出入口是一个目录,为了找到正确的出入口文件,将执行以下动作:

-   检查一个 package.json 文件是否存在 `main` 字段。 条目文件将是 `main` 字段,相对于 package.json 目录.
-   检查是否为 `index.ts` 文件存在于给定目录中.
-   检查给定目录中是否存在一个eponym文件.
-   检查是否带有该词的缩写文件 `.ts` 扩展存在于给定的目录中.
-   检查是否为 `main.ts` 文件存在于给定目录中.
-   检查是否为 `index.js` 文件存在于给定目录中.
-   检查是否带有该词的缩写文件 `.js` 扩展存在于给定的目录中.
-   检查是否为 `main.js` 文件存在于给定目录中.

## API 密码

库导出一个函数,用于程序上执行 Typescript 文件.

```ts
import esrun from 'esrun'

export async function esrun(filePath: string, options?: Options): Promise<void>

export type Options = {
   // arguments to pass to the script
   args?: string[] = []

   // if true, will reload the script on file changes
   // you can also pass an additional array of globs to watch
   watch?: boolean | string[] = false

   // if true, prevent console clearing on watch mode
   preserveConsole?: boolean

   // if true, turn on inspect mode to use browser's console
   inspect?: boolean = false

   // if false, do not transform __dirname and __filename
   // (the CLI option to disable file constants is --noFileConstants)
   fileConstants?: boolean = true

   // if false, external packages will be bundled
   makeAllPackagesExternal?: boolean = true

   // if false, process.exit() won't be called after execution
   exitAfterExecution?: boolean = true

   // enable use of process.send() from the children
   interProcessCommunication?: boolean = false

   // additional options to pass to node's cli
   nodeOptions?: Record<string, Parameter> = {}

   // indicate the mode to use to run code
   // "cliParameters" means the code is passed to the node program
   // as parameters
   // "temporaryFile" means a temporary file is created inside
   // the node_modules folder, then executed, then deleted
   sendCodeMode?: "cliParameters" | "temporaryFile"

   // executed before the code is executed (after the build)
   beforeRun?: () => unknown

   // executed after the code is executed
   afterRun?: () => unknown
}
```

### 创建新运行程序以获取/ 转换生成的代码

要完全控制,您可以创建自己的脚本运行例 :

```ts
import { Runner } from 'esrun'

const runner = new Runner(inputFile: string, options?: Options)

// build the given file and all its dependencies
await runner.build(buildOptions?: BuildOptions)

// you can see what the generated code is
console.log("Generated javascript code:", runner.outputCode)

// you can apply transformations to the code
await runner.transform(code => `console.log('Hello world!');\n` + code)

// then execute the build and return the given status
const status = await runner.execute()
```

### 接收数据

您可以打开选项从执行的脚本接收数据 `interProcessCommunication`。 。 。 .

当选项打开时,脚本可以调用 [process.send(消息:字符串)](https://nodejs.org/api/process.html#processsendmessage-sendhandle-options-callback)。 。 。 .

执行结束时,发送的信息将通过 `runner.output`。 。 。 .

假设你有以下文件 `helloWorld.ts`数字 :

```ts
// helloWorld.ts
process.send('Hello world')
```

然后,您可以这样接收数据fro这个脚本:

```ts
const runner = new Runner('helloWorld.ts', { interProcessCommunication: true })

await runner.execute({ exitAfterExecution: false })

console.log("Received data:", runner.output)
// should log 'Received data: Hello world'
```

## 更改日志

已有更改日志 [这里](https://github.com/digital-loukoum/esrun/blob/main/CHANGELOG.md)。 。 。 .

## 常见问题

### @digitak/esrun 是什么？

使用 Esbuilding 直接执行您的 Typescript 文件

### 如何安装 @digitak/esrun？

在项目目录运行 npm install @digitak/esrun，或使用 pnpm add / yarn add / bun add。它还提供命令行工具 esrun，可以用 npx esrun 直接运行。

### @digitak/esrun 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @digitak/esrun 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @digitak/esrun 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=14\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @digitak/esrun 可以商用吗？

@digitak/esrun 使用 ISC 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @digitak/esrun 的下载量有多少？

根据 npm 官方下载统计，@digitak/esrun 在 2026/10/12 – 2026/11/10 这 30 天内被下载 80,228 次，日均约 2,674 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @digitak/esrun 还在维护吗？

最新版本 3\.2\.26 发布于 2023/12/14（2 年前）；至今共发布 70 个版本，其中过去 12 个月发布了 0 个；首次发布于 2021/01/15。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

