Static Import in Ecmascript
Static imports support before ES10
, and Dynamic imports are not supported.
There is no import support before ES6, ES6 introduced import and export features.
Below is an example of static import in javascript.
mymodule
is created and exported using the export keyword
// mymodule.js
export function getMessage() {
return "Hello world";
}
import mymodule
using the import
keyword
// main.mjs
import { getMessage } from './mymodule.js';
let message = getMessage(); // output "Hello world";
Important points that were achieved with static import
- Static imports declare at top of the file only.
- Not allowed importing where ever required like in event handlers or conditional expression ie if statements
- Imports the functionality at compile time only
- Advantages with static are bundling library and tree shaking
- It has a module specifier(./mymodule.js) that is fixed and will not change at runtime
Disadvantages with static imports
- Import the modules wherever required instead of fixed import.
- Change Module specifier at runtime is not possible
- import modules in regular script files
- assign the imports to variables
All the disadvantages of static imports are solved in the ES10 Dynamic imports feature.
Dynamic Import
It introduced a new function syntax form import(moduleSpecificer)
that returns the retrieved module promise.
It retrieves the module, and its dependencies and initializes the modules.
Here is a syntax for dynamic import
import(moduleSpecifier)
The parameters are
- accepts
moduleSpecifier
as input - returns a promise of the request module
const mymoduleSpecifier = './mymodule.js';
import(mymoduleSpecifier)
.then((module) => {
module.getMessage();// outputs Hello world
});
import() returns promises, so we can also replace them with async and await feature
async and await dynamic import example As you see in the below example, import specifier assigned to variable using await in an async block of code.
(async () => {
const mymoduleSpecifier = './mymodule.js';
const module = await import(mymoduleSpecifier)
module.getMessage();// outputs Hello world
})();
Browser Support
This feature supports the following browser versions.
- Chrome 63+
- Firefox 67+
- Safari 11.1
- Babel plugin
Babel plugin-syntax-dynamic-import To install this feature nodejs applications, Please add plugin-syntax-dynamic-import as devDependencies.
npm install --save-dev @babel/plugin-syntax-dynamic-import
configure.babelrc file by adding plugins entry as follows
{
"plugins": ["@babel/plugin-syntax-dynamic-import"]
}