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

终端为何陷入提问无限循环?(附Node.js相关代码)

问题分析与解决

核心问题1:重复提问

你把inquirer.prompt(questions)放在了文件遍历的for循环里,每处理一个文件就会触发一轮提问,所以终端会一直重复弹出问题。

核心问题2:占位符替换&文件名修改失败

  • 你定义的slug问题name是test-plugin,但后面修改文件名时用了answers['plugin_slug'],键名不匹配,根本拿不到用户输入的slug值,导致文件名改不了,占位符也替换错误。
  • 另外,你用的GitHub链接是网页的/tree/main路径,这不是有效的Git克隆地址,克隆会出错,得换成仓库的Git地址。

修复后的完整代码

#!/usr/bin/env node

import { program } from 'commander';
import { execa } from 'execa';
import inquirer from 'inquirer';
import fs from 'fs';
import path from 'path';

program
  .command('make-plugin <folder-name>')
  .description('Clone repo and change values')
  .action(async (folderName) => {
    // 修复:使用正确的Git仓库地址,移除/tree/main后缀
    const repoURL = 'https://github.com/wpdev95/plugin-boiler.git';
    const targetFolder = path.resolve(process.cwd(), folderName);

    // 克隆仓库
    await execa('git', ['clone', repoURL, folderName]);

    // 修复:将提问逻辑移到文件遍历循环外,仅执行一次
    const questions = [
      {
        type: 'input',
        name: 'pluginName', // 改用规范变量名,避免空格和特殊字符
        message: '请输入你的插件名称?',
      },
      {
        type: 'input',
        name: 'pluginSlug', // 统一变量名,方便后续调用
        message: '请输入你的插件别名(slug)?',
      },
      {
        type: 'input',
        name: 'pluginAuthor',
        message: '请输入作者名称?',
      },
    ];
    // 仅执行一次提问,获取所有用户输入
    const answers = await inquirer.prompt(questions);

    // 遍历文件并替换占位符
    const files = fs.readdirSync(targetFolder);

    for (const file of files) {
      const filePath = path.join(targetFolder, file);
      let content = fs.readFileSync(filePath, 'utf-8');

      // 替换内容中的占位符
      for (const key in answers) {
        const placeholder = `{{${key}}}`;
        const replacement = answers[key];
        content = content.replace(new RegExp(placeholder, 'g'), replacement);
      }

      // 修改PHP文件名
      if (file === 'plugin-boilerplate.php') {
        // 修复:使用正确的键名获取slug值
        const newPhpFileName = `${answers.pluginSlug}.php`;
        const newPhpFilePath = path.join(targetFolder, newPhpFileName);
        // 优化:先写入修改后的内容,再重命名,避免文件移动后写入失败
        fs.writeFileSync(filePath, content, 'utf-8');
        fs.renameSync(filePath, newPhpFilePath);
        continue; // 跳过后续写入操作,避免重复处理
      }

      // 将修改后的内容写回文件
      fs.writeFileSync(filePath, content, 'utf-8');
    }

    console.log('插件模板创建成功!愉快编码!:D');
  });

program.parse(process.argv);

额外优化说明

  • 把问题的name改成了驼峰命名(如pluginName),避免空格和特殊字符导致的键名混乱。
  • 调整Git克隆地址为有效仓库地址,确保能正确拉取代码。
  • 优化了文件重命名的顺序,先写入内容再重命名,避免出现文件不存在的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 23:20:00