Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I don't understand what is wrong.

(我不明白怎么了。)

Node v5.6.0 NPM v3.10.6

(节点v5.6.0 NPM v3.10.6)

The code:

(代码:)

function (exports, require, module, __filename, __dirname) {
    import express from 'express'
};

The error:

(错误:)

SyntaxError: Unexpected token import
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:387:25)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)
    at startup (node.js:140:18)
    at node.js:1001:3
  ask by SofDroid translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
432 views
Welcome To Ask or Share your Answers For Others

1 Answer

Update 3: Since Node 13 , you can use either the .mjs extension, or set "type": "module" in your package.json.

(更新3:Node 13开始 ,您可以使用.mjs扩展名,也可以在package.json中设置“ type”:“ module”。)

You don't need to use the --experimental-modules flag.

(你并不需要使用--experimental-modules的标志。)

Update 2: Since Node 12 , you can use either the .mjs extension, or set "type": "module" in your package.json.

(更新2:节点12开始 ,您可以使用.mjs扩展名,也可以在.mjs设置"type": "module" 。)

And you need to run node with the --experimental-modules flag.

(并且您需要使用--experimental-modules标志运行节点。)

Update: In Node 9 , it is enabled behind a flag, and uses the .mjs extension.

(更新:节点9中 ,它在标志后面启用,并使用.mjs扩展名。)

node --experimental-modules my-app.mjs

While import is indeed part of ES6, it is unfortunately not yet supported in NodeJS by default, and has only very recently landed support in browsers.

(虽然import确实是ES6的一部分,但是不幸的是,默认情况下NodeJS尚未支持import ,并且最近才在浏览器中提供支持。)

See browser compat table on MDN and this Node issue .

(请参阅有关MDN的浏览器兼容表以及此Node问题 。)

From James M Snell's Update on ES6 Modules in Node.js (February 2017):

(摘自James M Snell 关于Node.js中ES6模块更新 (2017年2月):)

Work is in progress but it is going to take some time — We're currently looking at around a year at least.

(工作正在进行中,但将需要一些时间-我们目前至少需要一年左右的时间。)

Until support shows up natively, you'll have to continue using classic require statements:

(在本地显示支持之前,您必须继续使用经典的require语句:)

const express = require("express");

If you really want to use new ES6/7 features in NodeJS, you can compile it using Babel.

(如果您确实想在NodeJS中使用ES6 / 7的新功能,则可以使用Babel对其进行编译。)

Here's an example server .

(这是一个示例服务器 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...