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

将yargs配置移至独立文件后,.argv._[0]返回undefined的原因?

问题分析与解决

你遇到的TypeError: Cannot read property '_' of undefined错误,核心原因非常明确:你的yargs.conf.js文件没有把配置好的argv对象导出,导致主文件app.js里通过require('./yargs.conf.js')拿到的是一个空对象,自然访问不到argv._这个属性。

修复步骤

1. 修改yargs.conf.js,导出配置好的argv

在配置文件的最后一行,添加导出语句即可:

const yargs = require('yargs');
const titleOptions = {
    describe: 'Title of note',
    demand: true,
    alias: 't'
};
const bodyOptions = {
    describe: 'Body of the note',
    demand: true,
    alias: 'b'
};
const argv = yargs
    .command('add', 'Add a new note', {
        title: titleOptions,
        body: bodyOptions
    })
    .command('list', 'Lists all notes')
    .command('read', 'Reads individual note to the screen', {
        title: titleOptions
    })
    .command('remove', 'Removes selected note', {
        title: titleOptions
    })
    .help()
    .argv;

// 新增这行,把配置完成的argv暴露给外部模块
module.exports = argv;

2. 验证主文件逻辑

主文件app.js里的代码不需要任何修改,现在yg变量会正确获取到导出的argv对象,执行list或者其他命令时,就能正常访问yg.argv._[0]并触发对应的逻辑了。

额外补充

Node.js模块默认导出的是一个空对象,除非你显式用module.exports或者exports指定要对外暴露的内容。你之前的配置文件只完成了yargs的命令配置工作,但没有把最终生成的argv对象传递给外部模块,这才导致了属性访问失败的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:10:12