nodejs 8 import module - require or import? [dupli

2019-01-22 11:28发布

This question already has an answer here:

Just wonder how do we import a module in node.js 8 - are we still using require?

Or do we still need babel for using import?

I have been digging around but seems no answer. If we still have to use require, why can't node implement import yet?

1条回答
相关推荐>>
2楼-- · 2019-01-22 12:12

UPDATE-2018.11.15 ↓

Short answer
We're still using require

Long answer
ESM loading has partially landed in node 8.5.0 which was released in September 2017. As such, it has beeen part of the specs as an experimental feature for a little while: see the API documentation here. Caveats include the need for the --experimental-modules flag and the use of a new .mjs extension for modules.

There is still changes that need to happen in V8 before ESM loading is stable and fully featured so as with my original answer, I would still advise on sticking with CommonJS require if you don't already use Babel for other stuff

See this post for a more didactic explanation


PREVIOUS ANSWER ↓

The two implementations are completely different under the hood, so there is more to it than what meets the eyes

The takeaway is that there are still lingering issues/questions over the specifications (all the way to V8), and as such import cannot currently be implemented in Node without a using a transpiler

See this comment (dated February 2017) from one of the contributor:

At the current point in time, there are still a number of specification and implementation issues that need to happen on the ES6 and Virtual Machine side of things before Node.js can even begin working up a supportable implementation of ES6 modules. Work is in progress but it is going to take some time — We’re currently looking at around a year at least.

Keep in mind that transpilers simply converts the ES6 module syntax to the CommonJS module syntax, so there is currently no performance benefits. In other words, if you don't have a Babel pipeline already, there is not much incentives to create one just to use the new proposed import syntax, except from a proactive syntactic perspective

For more details on how the implementation differs, see this write up

查看更多
登录 后发表回答