"require(x)"与"require(x)"之间的区别在于:和“导入x" [英] The difference between "require(x)" and "import x"
问题描述
我刚刚开始研究一个将与MongoDB交互的小型节点项目.但是,即使我已经通过npm
正确安装了它们,我似乎也无法正确导入相关的节点模块.
例如,以下代码引发错误,告诉我"express没有默认导出":
import express from "express";
但是,此代码有效:
const express = require("express");
所以我的问题是,导入方法和变量/请求方法的功能有什么区别?我想修复困扰导入项目的所有内容,因为这似乎很可能会导致其他问题.
这个简单的图表可以帮助我理解require
和import
之间的区别.
除此之外,
您不能仅使用require
有选择地加载您需要的作品,而使用imports
,您可以有选择地仅加载您需要的作品. 那可以节省内存.
require
,import
的加载是同步(逐步),因此import
可以是异步的(无需等待先前的导入),因此的性能比 require
.I've just started working on a small node project that will interface with a MongoDB. However, I cannot seem to get the relevant node modules to import correctly, even though I have installed them correctly via npm
.
For example, the following code throws an error, telling me that "express has no default export":
import express from "express";
However, this code works:
const express = require("express");
So my question is, what is the difference in how the import and variable/require methods function? I'd like to fix whatever is plaguing my imports on the project, as it seems likely to cause additional problems down the road.
This simple diagram that helps me to understand the difference between require
and import
.
Apart from that,
You can't selectively load only the pieces you need with require
but with imports
, you can selectively load only the pieces you need. That can save memory.
Loading is synchronous(step by step) for require
on the other hand import
can be asynchronous(without waiting for previous import) so it can perform a little better than require
.
这篇关于"require(x)"与"require(x)"之间的区别在于:和“导入x"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!