Static imports refer to the feature of handling native JavaScript modules (JS modules, ES modules, or ECMAScript modules) by using import and export statements, entire module graph needs to be downloaded and executed before main code can run.
// utils.js
// named export
export const NAME = 'Anonymous'
// default export
export default function hello(name) {
console.log(`Hello ${name}`)
}
Named exports are useful to export several values. During the import, one will be able to use the same name to refer to the corresponding value. Concerning the default export, there is only a single default export per module. A default export can be a function, a class, an object or anything else. This value is to be considered as the main exported value since it will be the simplest to import.
// index.js
import hello, {NAME} from './utils'
hello(NAME)
Static imports are static declarations, they accept a string literal as the module specifier, and will always result in all code in the imported module being evaluated at load time.
Static imports introduce live bindings into the local scope via a pre-runtime linking process. Bindings imported are called live bindings because they are updated by the module that exported the binding.
Although imported features are available in the file, they are read only views of the feature that was exported. You cannot change the variable that was imported, but you can still modify properties similar to const
. Additionally, these features are imported as live bindings, meaning that they can change in value even if you cannot modify the binding unlike const
.
Imported modules are in strict mode whether you declare them as such or not. The import
statement cannot be used in embedded scripts unless such script has a type="module"
.
Static imports are statically analyzable, and it can thus help bundler tools optimize your code by tree shaking. Static imports are more than just syntax, they are a critical tooling feature.
Static imports are designed for the 90% case, useful for initial paint dependencies, especially for above-the-fold content. You must use dynamic imports when you want to import modules dynamically conditionally at run time, compute the module specifier, or import a module from within a regular script.