esbuild watch模式报错:无法写入输出文件(用户映射节已打开)
esbuild watch模式重复修改后文件占用报错的解决思路
问题场景
使用esbuild 0.17.14版本,配置文件esbuild.config.js如下:
// fileName: esbuild.config.js import esbuild from "esbuild"; import glob from "glob"; const context = await esbuild.context({ entryPoints: glob.sync("src/*.js"), bundle: true, minify: true, sourcemap: false, outdir: "dist", format: "esm", splitting: false, metafile: true, // loader: { // ".png": "file", // ".svg": "file", // }, write: true, logLevel: "info", }) .catch(() => process.exit(1)); await context.watch()
在watch模式下修改文件几次后,必现报错:
Failed to write to output file: open D:\Users\anonymized_path\dist\page.js: The requested operation cannot be performed on a file with a user-mapped section open.
停止watch重新构建可正常运行,已尝试关闭浏览器、Live Server、删除输出文件等操作,问题仍存在。
解决步骤
- 优先升级esbuild版本:0.17.14属于较旧版本,这类文件占用bug在后续版本中大概率已修复。执行命令升级:
npm install esbuild@latest - 排查Windows系统级文件锁定:Windows下杀毒软件、OneDrive等同步工具、系统索引服务都可能锁定dist目录的文件。暂时关闭这类工具,再测试watch模式是否正常。
- 修改输出目录测试:临时把
outdir改成dist-temp,排除原dist目录存在的权限或特殊锁定问题。 - 禁用VS Code非必要插件:除了Live Server,像代码格式化、静态文件预览类插件也可能后台读取输出文件,尝试禁用所有插件后重启VS Code再测试。
- 添加esbuild配置参数:尝试在context配置中加入
incremental: true,强制开启增量构建,可能缓解文件占用问题:const context = await esbuild.context({ // 原有配置... incremental: true, })
内容的提问来源于stack exchange,提问作者Konstantinos Kornarakis
相关产品推荐
相关产品推荐

