Require and import do the same thing differently.
I never said to none about missin’ the good ol’ days. The days when Javascript was not golden, code could be simply included within HTML or a single file, and when smarty-pants use to go cyber without Javascript. Those were more of WTF-days.
Now, Javascript comes in a million files per app and in beautiful billion packages. That give us new challenges to solve - like how to include and reference them scripts across files.
We have already seen that. That’s easy - just use require
.
|
|
The require
statement was used for the last thousand years and people seemed to be happy about them. Except when they weren’t, and used use
or some other freakish statements to reference functions in other files.
Once JS is referenced using require
you can use functions/methods within them in more than one way (incl. this singleton pattern which you shouldn’t use).
For example: here’s the class that needs to be referenced elsewhere.
|
|
Account.js file is referenced in the below source file.
|
|
You may have a thousand such JS files in packages, your own code / modules that you have carefully written, and all of them existing in different folders. The files may be as simple as having three lines or a hundred functions within them.
There had to be a better way to import them. Yes - import
.
|
|
This works similar to require
but is also a super-set and alter-ego in one.
|
|
Use only parts of the Account.js
code like so -
|
|
import
allows you to statically declare what components you want your function to reference from a third party file.
The old way of importing the entire file exists too..
|
|
import
was introduced in ES6 to not only provide a cleaner(?) reference, but also to -
- selective loading of components / functions / variable
- async loads enabled
- use promises
Should you use require
at all? Well, yes -
- import gets transpiled to the
require
format anyway in some engines - you want to use a different name to reference the imported function.
import
is more static - do dependency management through synchronous loading of external files