本文介绍了如何在节点中使用es6导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将ES6导入挂起,并尝试使用此示例中提供的语法:

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

我正在浏览支持表,但是找不到支持新导入语句的版本(我尝试查找文本导入/要求),我目前正在运行节点8.1.2,并且还认为,由于备忘单是指.js文件,因此它应该与.js文件一起使用.

I'm looking through the support table, 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';

我得到了错误:

SyntaxError: Unexpected token import.

我要导入的对lib的引用:

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));
}

我缺少什么?如何获得node来识别我的import陈述?

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

推荐答案

TLDR;

节点> = v13

在Node 13及更高版本中,这非常简单.您需要:

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

  • 使用.mjs扩展名保存文件,或
  • 在最近的package.json中添加{ "type": "module" }.
  • Save the file with .mjs extension, or
  • Add { "type": "module" } in the nearest package.json.

您只需要执行上述一项操作就可以使用ES模块.

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

节点< = v12

如果您使用的是节点版本8-12,请使用扩展名为.mjs的ES6模块保存文件,然后按以下方式运行文件:

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

node --experimental-modules my-app.mjs

这篇关于如何在节点中使用es6导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 06:15
查看更多