Join the Nature Wishlist Discord to get help, share your projects, and discuss JavaScript.
⚡️ ⏐ Performance Patterns
2. Static Import

Static Import

Import code that has been exported by another module


Overview

A statically imported module is a module that's imported with the default import keyword.

import module1 from "./module1";
import module2 from "./module2";
import module3 from "./module3";

In this case, module1, module2, and module3 are statically imported.


When a module is statically imported, a bundler traverses all the modules, and bundles them into one file.

Let's say we have four files:

  1. module1.js, which exports as single function module1
  2. module2.js, which statically imports the named export module1, and returns a single function module2
  3. module3.js, which statically imports the named export module2, and returns a single function module3
  4. index.js, which statically imports the named export module3 and logs this value

When we bundle index.js, the bundler traverses the modules, and bundles them all together into one single file.


Implementation

We can import React components from other files.

import Header from "./Header";
import Content from "./Content";
 
export default function BlogPost({ post }) {
  return (
    <div>
      <Header title={post.title} />
      <Content body={post.body} />
      <Footer />
    </div>
  );
}

In this case, Header and Content are statically imported. The Header and Content modules get executed as soon as the engine reaches the line on which we import them.

When you open the console, you can see the order in which the modules have been loaded!


Tradeoffs

Loading instant dependencies: Statically imported components are instantly available to the user

Optimizations: Statically imported modules can be statically analyzed and tree-shaken.

Large bundle size: When importing all modules, you might include code that won't be necessary