如何在Yeoman生成器中无需终端确认直接删除文件?
解决Yeoman生成器程序化删除文件不触发确认提示的方案
方案一:用Node.js原生文件系统模块直接删除
Yeoman生成器基于Node.js运行,完全可以跳过this.fs.delete,直接调用Node原生fs模块删除文件/目录,彻底绕开Yeoman的交互确认逻辑:
异步删除(推荐,避免阻塞流程)
const fs = require('fs').promises; // 在生成器的写入逻辑中使用 await fs.rm(`${rootDestinationPath}/${filePath}`, { force: true, // 强制删除,文件不存在也不会报错 recursive: true // 如果目标是目录,递归删除内部所有内容 });
同步删除
如果你的逻辑是同步执行的,可使用fs.rmSync:
const fs = require('fs'); fs.rmSync(`${rootDestinationPath}/${filePath}`, { force: true, recursive: true });
方案二:配置Yeoman禁用交互提示
Yeoman的this.fs底层依赖mem-fs-editor,删除提示和Yeoman的交互系统绑定。你可以在生成器初始化时临时禁用所有交互:
module.exports = class extends Generator { constructor(args, opts) { super(args, opts); // 全局禁用交互提示 this.options.force = true; // 或者单独给文件操作实例配置强制模式 this.fs._editor.force = true; } writing() { // 此时调用delete不会弹出确认提示 this.fs.delete(`${rootDestinationPath}/${filePath}`); } };
注意:this.fs._editor是直接访问mem-fs-editor的内部实例,属于非公开API,未来版本可能有变动,但当前版本可正常使用。
方案三:给this.fs.delete传force参数
mem-fs-editor的delete方法其实支持force选项,用来跳过确认提示,只是文档不够显眼:
this.fs.delete(`${rootDestinationPath}/${filePath}`, { force: true });
内容的提问来源于stack exchange,提问作者Alexandre Queiroz de Oliveira
相关产品推荐
相关产品推荐

