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

在OpenCLI命令中使用Inquirer遭遇模块导入错误求助

解决oclif项目中Inquirer的ERR_REQUIRE_ESM错误

原因

Inquirer v9及以上版本改为纯ESM模块,而oclif默认创建的新项目是CommonJS格式,两者模块加载机制不兼容,导致报错。

解决方案

方案1:降级Inquirer到支持CommonJS的版本

直接安装v8.x版本的Inquirer,该版本同时支持CommonJS和ESM:

npm install inquirer@8

导入方式用CommonJS语法:

// JavaScript项目
const inquirer = require('inquirer');
// TypeScript项目
import inquirer = require('inquirer');

方案2:将oclif项目转为ESM格式

  1. 在项目根目录的package.json中添加:
    "type": "module"
    
  2. 修改tsconfig.json(TypeScript项目)的配置:
    {
      "compilerOptions": {
        "module": "ESNext",
        "moduleResolution": "node16",
        "target": "ES2020"
      }
    }
    
  3. 使用ESM风格导入Inquirer:
    import inquirer from 'inquirer';
    

方案3:使用oclif内置的交互提示工具

oclif的@oclif/core自带prompt能力,无需额外安装Inquirer,直接使用:

import { Command } from '@oclif/core';

export default class MyCommand extends Command {
  async run() {
    // 文本输入提示
    const username = await this.prompt('请输入用户名');
    // 确认提示
    const confirm = await this.confirm('确认执行操作吗?');
    
    this.log(`用户名:${username},确认状态:${confirm}`);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 16:31:03