ES6, also known as ECMAScript 6 or ECMAScript 2015, introduced a standardized module format to JavaScript. This means that we can now organize and modularize JavaScript code into reusable pieces that we can import and export among our different code files. One crucial keyword to achieve this is the import
keyword.
The import
keyword in ES6 is used to import bindings that are exported from another module. In simpler words, we use import
to bring in the functions, objects, variables, or values from another JavaScript file or module into the current file we are working on.
Here is an example:
// file1.js
export const greeting = 'Hello, World!';
// file2.js
import { greeting } from './file1';
console.log(greeting); // Outputs: Hello, World!
In this example, we have a file named file1.js
that exports a constant called greeting
. We can then import this greeting
constant into another file file2.js
using the import
keyword.
Do remember that the import
statement is static, meaning it's run during the loading of the script and not in runtime. It adds a bit of predictability to your code, but it also means we can't conditionally import a module.
It's important to note that the import
keyword is not interchangeable with other keywords such as require
(popularized by Node.js for module importing), include
(from PHP and not part of JavaScript), or load
(from certain JavaScript environments). These other keywords are not technically a part of the ECMAScript specification and work in different ways.
The ES6 import
keyword is the current best practice to import modules in modern JavaScript.
Using the import
and export
keywords to manage your code, encourages encapsulation, increases code reusability and aids in keeping your codebase clean and organized.