How can I use an es6 import in node?

2019-01-02 20:31发布

I'm trying to get the hang of es6 imports in node and am trying to use the syntax provided in this example:

Cheatsheet Link: https://hackernoon.com/import-export-default-require-commandjs-javascript-nodejs-es6-vs-cheatsheet-different-tutorial-example-5a321738b50f

I'm looking through the support table: http://node.green/, but 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 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 cheatsheet's 1st example):

import { square, diag } from 'lib';

I get the error: SyntaxError: Unexpected token import.

Reference to lib 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?

8条回答
人气声优
2楼-- · 2019-01-02 21:13

Node.js has included experimental support for ES6 support. Read more about here: https://nodejs.org/api/esm.html.

TLDR; Save the file with ES6 modules with .mjs extension and run it like:

node --experimental-modules my-app.mjs

Node.js doesn't support ES6 modules. This blog by James describes the reasons for it. Though you can use Babel to use ES6 modules syntax.

查看更多
梦寄多情
3楼-- · 2019-01-02 21:15

You may try esm.

Here are some introduction: https://www.npmjs.com/package/esm

查看更多
登录 后发表回答