设置
要求
- Linux、macOS 或 Windows
- JavaScript 运行时
- Node.js >= 12.17.0
- Bun >= 1.0.0
- Deno 1.x, 2.x
- GraalVM Node.js
- 某种 bash 或 PowerShell
安装
bash
npm install zx # add -g to install globally
bash
npx zx script.js # run script without installing the zx package
npx zx@8.5.0 script.js # pin to a specific zx version
bash
yarn add zx
bash
pnpm add zx
bash
bun install zx
bash
deno install -A npm:zx
# zx requires additional permissions: --allow-read --allow-sys --allow-env --allow-run
bash
npx jsr add @webpod/zx
deno add jsr:@webpod/zx
# https://jsr.deno.org.cn/docs/using-packages
bash
docker pull ghcr.io/google/zx:8.5.0
docker run -t ghcr.io/google/zx:8.5.0 -e="await \$({verbose: true})\`echo foo\`"
docker run -t -i -v ./:/script ghcr.io/google/zx:8.5.0 script/t.js
bash
brew install zx
频道
zx 以多个版本分发,每个版本都有自己的一组功能。
详细比较:versions。
请仔细检查下载来源。 官方链接
Github
直接从 GitHub 获取 zx
bash
# Install via git
npm i google/zx
npm i git@github.com:google/zx.git
# Fetch from the GH pkg registry
npm i --registry=https://npm.pkg.github.com @google/zx
Docker
如果您更喜欢在容器中运行脚本,您可以从 ghcr.io 中拉取 zx 镜像。node:22-alpine 被用作基础。
shell
docker pull ghcr.io/google/zx:8.5.0
docker run -t ghcr.io/google/zx:8.5.0 -e="await \$({verbose: true})\`echo foo\`"
docker run -t -i -v ./:/script ghcr.io/google/zx:8.5.0 script/t.js
Bash
zx 主要依赖于 bash,因此请确保您的环境中可以使用它。 如果您使用的是 Windows,请考虑使用 适用于 Linux 的 Windows 子系统 或 Git Bash。 默认情况下,zx 查找 bash 二进制文件,但您可以通过调用 usePowerShell()
或 usePwsh()
切换到 PowerShell。
js
import { useBash, usePowerShell, usePwsh } from 'zx'
usePowerShell() // Use PowerShell.exe
usePwsh() // Rely on pwsh binary (PowerShell v7+)
useBash() // Switch back to bash
包
混合
zx 以 混合包 的形式分发:它同时提供 CJS 和 ESM 入口点。
js
import { $ } from 'zx'
const { $ } = require('zx')
它还具有内置的 TypeScript libdefs。 但需要在用户端安装 @types/fs-extra
和 @types/node
。
bash
npm i -D @types/fs-extra @types/node
ts
import { type Options } from 'zx'
const opts: Options = {
quiet: true,
timeout: '5s'
}
捆绑
我们使用 esbuild 来生成静态构建,这使我们能够一次性解决多个问题
- 减小 pkg 大小和安装时间。
- 使 npx(yarn dlx / bunx)调用可重现。
- 提供对各种 Node.js 版本的支持:从 12 到 23。
- 使审计更容易:完整的代码在一个地方。
复合
zx 导出多个针对不同用例的入口点
zx
– 主入口点,提供所有功能。zx/global
– 使用 zx 函数填充全局范围。zx/cli
– 从命令行运行 zx 脚本。zx/core
– 将 zx 模板生成器用作具有交替实用程序集的第三方库的一部分。
类型化
该库是用 TypeScript 5 编写的,并为 TS 用户提供全面的类型定义。
- Libdefs 通过 dts-bundle-generator 捆绑。
- 与 TS 4.0 及更高版本兼容。
- 需要安装
@types/node
和@types/fs-extra
。