在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格式
- 在项目根目录的
package.json中添加:"type": "module" - 修改
tsconfig.json(TypeScript项目)的配置:{ "compilerOptions": { "module": "ESNext", "moduleResolution": "node16", "target": "ES2020" } } - 使用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
相关产品推荐
相关产品推荐

