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);'
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 .
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.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With