Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can an ES6 module be run as a script in Node?

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?

like image 216
curiousdannii Avatar asked Jan 10 '18 03:01

curiousdannii


People also ask

Can you use ES6 modules in Node?

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.

How can ECMAScript modules be used natively in Node?

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.

Is an ES module file a .js file?

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.

Does Node support ES6 syntax?

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.


1 Answers

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.

like image 168
gibatronic Avatar answered Oct 21 '22 16:10

gibatronic