There seems to be some confusion when it comes to JavaScript modules.

Some developers are unsure of how they work and why are various ways that they can be used.

First, lets explore background of JavaScript modules.

An introduction on how to export and import JavaScript modules

JavaScript programs started as simple scripts or apps that had rather small codebases.

Node.JS had that ability for a while before it was incorporated in JavaScript with a feature called modules.

Eventually, they made it to the language itself and the browsers.

Article image

Now, lets take a look at an example.

To demonstrate the use of modules we will create a simpleusermodulethat will expose aUserclass.

To to do this, we need to make use of theexportstatement.

Article image

Imported modules are in strict mode whether you declare them as such or not.

The import statement cannot be used in embedded scripts unless a script has a bang out=module.

Bindings imported are called live bindings because theyre updated by the module that exported the binding.

Article image

Lets see it in our example:

Theimportstatement allows us to import specific bindings from a module.

There are several different ways to specify what were importing, and well discuss them later in this article.

For now, in our example, were just importingUserfrom the specified module, or file.

Article image

After importing, we can use that object as its part of the same file.

During the import, its mandatory to use the same name as the corresponding object.

But a default export can be imported with any name.

Article image

But here are more options when it comes to importing.

But this doesnt always have to be the case, you might also have dynamic imports.

What are dynamic imports?

Article image

This has some obvious performance advantages.

Lets read on and see how it works.

It returns a promise, which fulfills with a module object giving you access to that objects exports.

Article image

For example:

Combining default and named exports

Yes, you read that right.

I hope you enjoyed and learned something new today.

This article was originally published onLive Code StreambyJuan Cruz Martinez, founder and publisher of Live Code Stream.

Article image

Sign up for updates on everything related to programming, AI, and computer science in general.

Also tagged with

Article image

Article image

Article image

Article image

Article image

Article image