How to publish a package to NPM with custom CLI

Asked

Viewed 69 times

-1

I created a folder structure developed for project in Nodejs, but I would like to publish it in NPM with a custom CLI, so that it was possible to choose what to install, something like: myPackageName --beta=server where this would install only the server folder, or myPackageName --beta=webdevelopment where this would install only webdevelopment folder.

In case this myPackageName would be available after installing the main project via npm.

  • What language is this installer in? Node? bash? other?

  • Would be in Nodejs

1 answer

0

In these cases what is done is to publish a package with the product name, but with an external layer that is the installer itself. That is, when downloading the package it can not use, only after running the myPackageName --beta=server. And in that case it would be better to give it another name.

That means you have a program instalador.js where you can read the arguments passed to the script deploy (you can of course change this name). That file would have something like:

const args = process.argv;
const envVariables = args
  .slice(2)
  .join("")
  .split("--")
  .filter(Boolean)
  .reduce((vars, envVar) => {
    const [key, value] = envVar.split("=");
    return { ...vars, [key]: value };
  }, {});

console.log(envVariables);

With this code you could use for example:

node instalador --beta=server --lang=en

and within the file it would return:

{ beta: 'server', lang: 'en' }

That is, you can go on and add to that code the rest of logic knowing that envVariables.beta has the value you seek.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.