-->

How can I use an es6 import in node?

2019-01-02 21:02发布

问题:

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?

回答1:

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.



回答2:

Wasted about 3 hours.

I just wanted to use the import and export in js files.

Everyone says not possible. But, as of May 2018, it's possible to use above in plain node.js, without any modules like babel, etc.

Here is a simple way to do it.

Create below files, run and see output for yourself.

Also don't forget to see Explanation below.

myfile.mjs

function myFunc() {
    console.log("Hello from myFunc")
}

export default myFunc;

index.mjs

import myFunc from "./myfile"

myFunc();

run

node  --experimental-modules  index.mjs

output

(node:12020) ExperimentalWarning: The ESM module loader is experimental.

Hello from myFunc

Explanation:

  1. Since it is experimental modules, .js files are named .mjs files
  2. While running you will add "--experimental-modules" to the "node index.js"
  3. While running with experimental modules in the output you will see: "(node:12020) ExperimentalWarning: The ESM module loader is experimental. "
  4. I have current release of node js, so if I run "node --version", it gives me "v10.3.0", though the LTE/stable/recommended version is 8.11.2 LTS.
  5. Some day in future, you could use .js instead of .mjs, as the features you become stable instead of Experimental.
  6. More on experimental features, see: https://nodejs.org/api/esm.html

Hope that helped.



回答3:

If you are using the modules system on the server side, you do not need to use Babel at all. To use modules in NodeJS ensure that:

  1. Use a version of node that supports the --experimental-modules flag
  2. Your .js files must then be renamed to .mjs

That's it.

However and this is a big however, while your shinny pure ES6 code will run in an environment like NodeJS (at writing 9.5.0) you will still have the craziness of transpilling just to test. Also bear in mind that Ecma has stated that release cycles for Javascript are going to be faster, with newer features delivered on a more regular basis. Whilst this will be no problems for single environments like NodeJS, its a slightly different proposition for browser environments. What is clear is that testing frameworks have a lot to do in catching up. You will still need to probably transpile for testing frameworks. I'd suggest using jest.

Also be aware of bundling frameworks, you will be running into problems there



回答4:

Back to Jonathan002's original question about

"... what version supports the new ES6 import statements?"

based on the article by Dr. Axel Rauschmayer, there is a plan to have it supported by default (without the experimental command line flag) in Node.js 10.x LTS. According to node.js's release plan as it is on 3/29, 2018, it's likely to become available after Apr 2018, while LTS of it will begin on October 2018.



回答5:

You may try esm.

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



回答6:

solution

https://www.npmjs.com/package/babel-register

// this is to allow ES6 export syntax
// to be properly read and processed by node.js application
require('babel-register')({
  presets: [
    'env',
  ],
});

// after that any line you add below that has typical es6 export syntax 
// will work just fine

const utils = require('../../utils.js');
const availableMixins = require('../../../src/lib/mixins/index.js');

below is definition of mixins/index.js

export { default as FormValidationMixin } from './form-validation'; // eslint-disable-line import/prefer-default-export

that worked just fine inside my node.js CLI app.



回答7:

I don't know if this will work for your case but I am running an express server with this:

nodemon --inspect ./index.js --exec babel-node --presets es2015,stage-2

This gives me the ability to import and use spread operator even though I'm only using node version 8.

You'll need to install babel-cli, babel-preset-es2015, babel-preset-stage-2 do do what I'm doing.



回答8:

  "devDependencies": {
    "@babel/core": "^7.2.0",
    "@babel/preset-env": "^7.2.0",
    "@babel/register": "^7.0.0"
  }

.babelrc

{
  "presets": ["@babel/preset-env"]
}

entry point node.js app

require("@babel/register")({})

// Import the rest of our application.
module.exports = require('./index.js')

Link How To Enable ES6 Imports in Node.JS https://timonweb.com/posts/how-to-enable-es6-imports-in-nodejs/



标签: