Bun是否支持通配符打包指定类型的TS/HTML文件?
Bun批量打包特定类型文件的实现方法
Bun本身的Bun.buildAPI没有直接提供indir或fileTypes这类配置,但可以通过以下方式实现批量打包特定类型文件的需求:
1. 在构建脚本中动态获取目标文件
你可以借助Node.js文件系统API或glob工具库,遍历目录筛选出指定后缀的文件,再将它们作为entrypoints传入Bun.build。
方法一:原生Node.js fs模块实现
// bun.build.js import { readdir } from 'fs/promises'; import { join } from 'path'; import html from 'bun-plugin-html'; // 定义扫描目录和目标文件后缀 const targetDir = './'; const targetExts = ['.html', '.ts']; // 筛选符合条件的文件 const entrypoints = []; const files = await readdir(targetDir); for (const file of files) { const ext = file.slice(file.lastIndexOf('.')); if (targetExts.includes(ext)) { entrypoints.push(join(targetDir, file)); } } // 执行构建 await Bun.build({ entrypoints, publicPath: "public", sourcemap: "inline", outdir: './public', plugins: [html()] });
方法二:用glob库简化写法
先安装glob依赖:
bun add glob -D
修改构建脚本:
// bun.build.js import { glob } from 'glob'; import html from 'bun-plugin-html'; // 通配符匹配所有html和ts文件 const entrypoints = await glob(['*.html', '*.ts']); await Bun.build({ entrypoints, publicPath: "public", sourcemap: "inline", outdir: './public', plugins: [html()] });
2. 命令行批量打包的说明
bun run *.ts无法直接实现批量打包,因为bun run是用来执行单个脚本文件的。如果要通过命令行批量处理,可以:
- 用shell循环实现,比如bash环境下:
for file in *.ts; do bun run "$file"; done - 或者直接执行你写的构建脚本,
bun bun.build.js这个命令是正确的(你更新后的判断没问题)。
补充:执行命令的确认
bun bun.build.js是直接运行构建脚本的正确方式,而bun run start是执行package.json中scripts字段定义的start命令,两者用途不同。
内容的提问来源于stack exchange,提问作者1.21 gigawatts
相关产品推荐
相关产品推荐

