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 of debate centering on which module standard should become the de-facto standard, what the syntax should look like, and how the implementation should work on the side of the interpreter. In the end, a consensus was reached on using import
and export
keywords to let the modules communicate with each other.
Babel was the first to implement a solution that was based on the previous standard of the specification. This implementation had to change in between, though, as updates were made to the standard. So when Webpack entered the scene, it implemented yet ...