7

Is it possible to run a command from a bin script in a package.json ? I know it expects a path to file and trying to run a command there results in an error upon installation (after publishing to npm). Is it possible to run a command like it is in an npm start ?

Examples:

{
  "name": "myscript",
  "version": "1.0.3",
  "bin": {
    "myscript": "app/main.js"
  }
}

This will create a symlink from the app/main.js script to /usr/local/bin/myscript
Instead, this is what I want to achieve:

{
  "name": "myscript",
  "version": "1.0.3",
  "bin": {
    "myscript": "echo hello world"
  }
}

Possible workarounds are also appreciated.

6
  • Not according to the docs: docs.npmjs.com/files/package.json#bin Commented May 8, 2018 at 22:32
  • Create a .sh file with the contents echo hello world and optionally add the header #!/usr/bin/env bash Commented May 8, 2018 at 22:34
  • @PatrickRoberts, any cross-platform similar solutions ? :) Commented May 8, 2018 at 22:35
  • @EvyatarMeged echo isn't cross-platform, so why should your bash file be? Commented May 8, 2018 at 22:35
  • @PatrickRoberts, good point, but it was for example's sake. Commented May 8, 2018 at 22:39

2 Answers 2

6

This answer is updated since the old answer was a bit dated and ultimately incorrect. You can now do:

npx myscript
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, but upon publication of the package, will I be able to run it with an alias of my choosing (in my example, I just need to call myscript after installation). Seems like I'll have to specify the key in scripts as well ?
What command do I run if I have "bin": "dist/src/cli.js", in my package.json? I've been doing node dist/src/cli.js but is there a simpler command? Ideally something that runs prepare before running the script too, because I need to compile the TypeScript.
2

Have you tried running npm link https://docs.npmjs.com/cli/link which would create a link to your binary, then you can just run your script on the command line as myscript.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.