问题描述
我刚刚开始从事一个将与 MongoDB 交互的小型节点项目.但是,我似乎无法正确导入相关的节点模块,即使我已经通过 npm
正确安装了它们.
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
.
例如,下面的代码抛出一个错误,告诉我express 没有默认导出":
For example, the following code throws an error, telling me that "express has no default export":
import express from "express";
但是,此代码有效:
const express = require("express");
所以我的问题是,import 和变量/要求方法的功能有何不同?我想修复项目中困扰我的导入的任何问题,因为它似乎可能造成更多问题.
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.
推荐答案
这个简单的图表将帮助您理解 require
和 import
之间的区别.
This simple diagram will help you understand the difference between require
and import
.
除此之外,
您不能使用require
选择性地仅加载您需要的部分,但是使用import
,您可以选择性地仅加载您需要的部分,可以节省内存.
You can't selectively load only the pieces you need with require
but with import
, you can selectively load only the pieces you need, which can save memory.
加载是同步(逐步)require
另一方面import
可以是异步的(无需等待先前的导入)所以它可以比 require
的性能好一点.
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"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!