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?
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 stuffSee 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 transpilerSee this comment (dated February 2017) from one of the contributor:
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 perspectiveFor more details on how the implementation differs, see this write up