How can an ES6 module be run as a script in Node?
When I try this shebang I get an error:
#!/usr/bin/env node --experimental-modules
/usr/bin/env: ‘node --experimental-modules’: No such file or directory
If I use this shebang it has syntax errors (of course):
#!/usr/bin/env node
SyntaxError: Unexpected token import
The work around I'm using is to use a shell script to call the module:
#!/usr/bin/env sh
BASEDIR=$( dirname "$0" )
node --experimental-modules $BASEDIR/script.mjs "$@"
Is it possible to get this working without a second file?
Node js doesn't support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error. For example, if we try to import express module by writing import express from 'express' node js will throw an error as follows: Node has experimental support for ES modules.
Authors can tell Node. js to use the ECMAScript modules loader via the . mjs file extension, the package. json "type" field, or the --input-type flag.
File Extensions By default, files with the . js extension will be treated as CommonJS modules, while files with the . mjs extension are treated as ES Modules. However, you might want to configure your NodeJS project to use ES Modules as the default module system.
ES6 brings new syntax and new features to make your code more modern and readable, and do more. ES6 requires you use Node. js version 13.
I've patched Ishan Thilina Somasiri solution to work with Node 13
without the .mjs
extension:
#!/usr/bin/env bash
":" //# comment; exec /usr/bin/env node --input-type=module - "$@" < "$0"
import { hostname } from 'os';
console.log(hostname());
The trick is pretty much the same, but using stdin, which is the only documented way when you don't have a package.json
nor the .mjs
extension. Thus, a standalone extensionless script.
However, global variables like __dirname
or __filename
won't be available.
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