tj / commander.js

node.js command-line interfaces made easy

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Using description returns undefined

elmeunick9 opened this issue · comments

This is a weird one. I'm using typescript + pnpm + esbuild. This is my "main.ts" file:

import { Command } from 'commander'
const program = new Command()

program
    .name('example')
    .description(process.env.npm_package_description)
    .version(process.env.npm_package_version)

And the scripts I have in "package.json":

    "scripts": {
        "start": "node dist/esm.js",
        "build": "npm run build:esm",
        "build:esm": "esbuild --bundle src/main.ts --format=esm --platform=node --outfile=dist/esm.js --packages=external",
    },

If I run npm start, it fails with an error:

TypeError: program.name(...).description(...).version is not a function

But if I run it with pnpm start everything works fine. Even more interesing, when I swap the "description" and version order, as in:

program
    .name('example')
    .version(process.env.npm_package_version)
    .description(process.env.npm_package_description)

Then everything works both with npm and pnpm.

Also it seems that using this order hides the description (probably that is why it works), is it supported?

Both .version() and .description() will return the current value if they are called with no argument, instead of returning the command for another chaining call. I suspect process.env.npm_package_description is undefined and the .description() call is acting as a getter and returning a string.

To avoid the problem without refactoring your code you could call like:

.description(process.env.npm_package_description ?? '')

That explains it. Thanks @shadowspawn.