You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Yeoman如何递归复制完整文件夹并对所有文件批量应用模板渲染?

Yeoman递归渲染整个目录模板文件解决方案

错误原因

你当前使用的this.fs.read和this.fs.write仅支持单文件操作,传入文件夹路径会触发路径校验失败报错,不需要手动遍历文件处理,Yeoman原生提供了专门的目录模板渲染API。

正确实现

直接使用Yeoman内置的this.fs.copyTpl方法,该方法原生支持递归遍历整个目录,自动对所有包含EJS模板标记的文件执行渲染,同时完整保留原目录结构:

'use strict';
const Generator = require('yeoman-generator');
module.exports = class extends Generator {
  writing() {
    this.fs.copyTpl(
      // 模板源目录路径
      this.templatePath('public'),
      // 输出目标目录路径
      this.destinationPath('public'),
      // 注入到所有模板的变量集合
      {
        webPageTitle : 'great web application',
        // 其他全局模板变量可直接在此处扩展
      }
    );
  }
};

可选优化

如果目录中包含不需要渲染的二进制静态资源(如图片、字体、压缩包等),可以增加过滤规则跳过渲染,提升执行效率:

this.fs.copyTpl(
  this.templatePath('public'),
  this.destinationPath('public'),
  { webPageTitle : 'great web application' },
  {},
  {
    globOptions: {
      // 配置不需要渲染的文件规则
      ignore: ['**/*.png', '**/*.jpg', '**/*.woff', '**/*.zip']
    }
  }
)

内容的提问来源于stack exchange,提问作者Franck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 06:36:04