Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use an ES6 import in Node.js? [duplicate]

I'm trying to get the hang of ES6 imports in Node.js and am trying to use the syntax provided in this example:

Cheatsheet Link

I'm looking through the support table, but I was not able to find what version supports the new import statements (I tried looking for the text import/require). I'm currently running Node.js 8.1.2 and also believe that since the cheatsheet is referring to .js files it should work with .js files.

As I run the code (taken from the cheatsheet's first example):

import { square, diag } from 'lib'; 

I get the error:

SyntaxError: Unexpected token import.

Reference to library I'm trying to import:

//------ lib.js ------ export const sqrt = Math.sqrt; export function square(x) {     return x * x; } export function diag(x, y) {     return sqrt(square(x) + square(y)); } 

What am I missing and how can I get node to recognize my import statement?

like image 583
Jonathan002 Avatar asked Aug 24 '17 06:08

Jonathan002


People also ask

How can I conditionally import an ES6 module?

To conditionally import an ES6 module with JavaScript, we can use the import function. const myModule = await import(moduleName); in an async function to call import with the moduleName string to import the module named moduleName . And then we get the module returned by the promise returned by import with await .

Is ES6 import asynchronous?

ES6 module loaders will be asynchronous while node.


1 Answers

Node.js has included experimental support for ES6 support. Read more about here: https://nodejs.org/docs/latest-v13.x/api/esm.html#esm_enabling.

TLDR;

Node.js >= v13

It's very simple in Node.js 13 and above. You need to either:

  • Save the file with .mjs extension, or
  • Add { "type": "module" } in the nearest package.json.

You only need to do one of the above to be able to use ECMAScript modules.

Node.js <= v12

If you are using Node.js version 9.6 - 12, save the file with ES6 modules with .mjs extension and run it like:

node --experimental-modules my-app.mjs 
like image 72
tbking Avatar answered Sep 26 '22 03:09

tbking