why node uses require not import?

核能气质少年 提交于 2020-01-13 08:58:10

问题


I'm learning node.js and am wondering why it uses the require syntax rather than the import syntax which React uses.

i.e.

const Validator = require("validator");

VS

import Validator from "validator";

I believed import is es6 but I don't think that explains why it's not used in node.


回答1:


the import and default are newer ES6 features, not yet used by node. Node is actually already implementing the new features as experiment though: with the --experimental-modules flag and only for files saved with .mjs extension.

Transpilers like babel make it possible to write modern, spec approved and /or experimental ECMAScript. In an ecosystem of bundlers like Webpack with transpilers like babel, it becomes easy to write maintainable, future-proof javascript, while the code remains widely suported because it's transformed to commonjs (the format you see recognizable byrequire (the old-school import) and module.exports (the old-school export).




回答2:


Probably for historical reasons. node.js and chrome (v8 engine) are older than ES6 standard.

On the other hand, see: How can I use an es6 import in node?

You may use import, too.




回答3:


I believed import is es6 but I don't think that explains why it's not used in node.

Just like the way NodeJS implements their entire library which tons of asynchronous functions which only support callback-based approach. Thinking this way and you'll realize that, sooner or later, the NodeJS framework will definitely support the import syntax and upgrade all of those asynchronous functions to support promise-based.



来源:https://stackoverflow.com/questions/52567493/why-node-uses-require-not-import

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!