gotchajavascriptCritical
The difference between "require(x)" and "import x"
Viewed 0 times
andbetweenthedifferencerequireimport
Problem
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
For example, the following code throws an error, telling me that "express has no default export":
However, this code works:
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.
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.
Solution
This simple image will help to you understand the differences between
Apart from that,
You can't selectively load only the pieces you need with
Loading is synchronous(step by step) for
require and import.Apart from that,
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.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.Context
Stack Overflow Q#46677752, score: 735
Revisions (0)
No revisions yet.