Import Syntax and JavaScript Modules
Learn about modules and how to export and import them in JavaScript.
We'll cover the following...
History
Modules in JavaScript are a bit of a special topic. JavaScript modules did not officially exist in the past, but there have been many attempts to introduce them. If you have been part of the development scene for a while, you might remember Asynchronous Module Definition (AMD), and if you have worked with Node.js before, you likely came across CommonJS modules, such as module.exports
and require('./myModule')
.
Note: AMD format is used to create modules in JavaScript and is targeted for use in browsers. This format proposes a particular way of defining modules so that modules and their dependencies can be loaded into the browser asynchronously. There are two key methods that you need to use when creating and consuming AMD modules:
define
methodsrequire
methodsThe idea is that we create a module using the global
define
method, and then we can import that module in other parts of the code using the globalrequire
method.On the other hand, in CommonJS, modules are loaded synchronously. We use
require()
to import modules in CommonJS. When implementing a module for other people to use, we can defineexports
, either named exports or a default export.
There has been a lot ...