Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to let npm package bin run with experimental-modules option?

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);'
like image 651
duXing Avatar asked Jan 31 '18 07:01

duXing


People also ask

How do I enable experimental modules?

In versions of Visual Studio before Visual Studio 2019 version 16.11, you can enable experimental modules support by use of the /experimental:module compiler option along with the /std:c++latest option. In Visual Studio 2019 version 16.11, module support is enabled automatically by either /std:c++20 or /std:c++latest .

How do I run a npm script in package json?

To define an NPM script, set its name and write the script under the 'scripts' property of your package. json file: To execute your Script, use the 'npm run <NAME-OF-YOUR-SCRIPT>' command. Some predefined aliases convert to npm run, like npm test or npm start, you can use them interchangeably.

How do I add a module to a package json?

To add dependencies and devDependencies to a package. json file from the command line, you can install them in the root directory of your package using the --save-prod flag for dependencies (the default behavior of npm install ) or the --save-dev flag for devDependencies.

How do npm modules work?

npm install downloads a package and it's dependencies. npm install can be run with or without arguments. When run without arguments, npm install downloads dependencies defined in a package. json file and generates a node_modules folder with the installed modules.


1 Answers

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/

like image 183
Patrick Lee Scott Avatar answered Sep 18 '22 08:09

Patrick Lee Scott