16

Starting in Node v8.5.0, support for ES6 style modules

import x from 'x'

has been available by running node using the option --experimental-modules, as below:

node --experimental-modules test.mjs

Using the bin key in package.json you can easily create cli tools npm cli, by running npm link.

Unfortunately, when running in this manner, node is called without the optional --experimental-modules flag.

How can you use bin modules with --experimental-modules?

Here is an example

bin/healthcheck.mjs

import { connect } from 'amqplib'

let open = connect(process.env.RABBITMQ_URL);

const exit = ({healthy = true}) => {
  return healthy ? process.exit(0) : process.exit(1)
}

open.then(() => {
  exit({healthy: true})
}).catch((e) => {
  exit({healthy: false})
})

package.json

{
  "name": "my-cli",
  "bin": {
    "healthcheck": "./bin/healthcheck.mjs"
  }
}

running...

> npm link
> healthcheck
/usr/local/bin/healthcheck: line 1: import: command not found
/usr/local/bin/healthcheck: line 3: syntax error near unexpected token `('
/usr/local/bin/healthcheck: line 3: `let open = connect(process.env.RABBITMQ_URL);'

1 Answer 1

12

You can use a shebang at the top of the script

#!/bin/sh 
":" //# comment; exec /usr/bin/env node --experimental-modules "$0" "$@"

More details here: http://sambal.org/2014/02/passing-options-node-shebang-line/

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

4 Comments

Nice Patrick! In my simple use case, I just have this one-liner at the top of my entry-point file: #!/usr/bin/env node --experimental-modules --no-warnings. Thanks!
it's shameful that in 2019, node still requires us to use this hack from early 2014 — so glad it works!
I get this error when it runs line 2: //#: No such file or directory. It continues running when I run it from Terminal, but it errs out in Sourcetree. Any idea if there is a way to solve? I removed "comment", and that didn't help.
Oops--nevermind--I see it was my adding a semicolon after ":"... Can't do that apparently

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.