Static Import

patternsdev/skills/javascript/static-import

作者 patternsdev48bf58a488cdMIT253 个星标收录于 2026年10月8日更新于 2026年10月8日仓库5个月前更新

Teaches static ES2015 import syntax for module dependencies. Use when you need to import code that is required at load time and benefits from static analysis and tree shaking.

AI 生成的概览

讲解 ES2015 静态 import 语法,以及何时应优先使用它而非动态导入模块依赖。

功能
该技能讲解 ES2015 静态 import 语法:使用默认 import 语句导入的模块会被加入初始打包文件。它通过一个聊天应用示例展示静态导入的组件,并说明静态导入的模块会在引擎执行到导入语句时立即运行。它还解释了打包体积的取舍,以及何时应改用动态导入。
适用场景
当需要导入在加载时立即需要、并能受益于静态分析和 tree shaking 的模块时使用。它也适合用来理解默认导入机制,从而判断何时应改用动态导入。
运行要求
无需任何工具、软件包或凭据;仅为说明性指令,不附带脚本。

Static Import

The import keyword allows us to import code that has been exported by another module. By default, all modules we're statically importing get added to the initial bundle. A module that is imported by using the default ES2015 import syntax, import module from 'module', is statically imported.

Let's look at an example! A simple chat app contains a Chat component, in which we're statically importing and rendering three components: UserProfile, a ChatList, and a ChatInput to type and send messages! Within the ChatInput module, we're statically importing an EmojiPicker component to be able to show the user the emoji picker when the user toggles the emoji.

When to Use

  • Use this for importing modules that are needed immediately on page load
  • This is the default import mechanism — understand it to know when to switch to dynamic imports

Instructions

  • Use static imports for modules critical to the initial render
  • Be aware that all statically imported modules are bundled into the initial bundle
  • Consider switching to dynamic imports for modules not needed on initial render

Details

The modules get executed as soon as the engine reaches the line on which we import them.

Since the components were statically imported, Webpack bundled the modules into the initial bundle:

bash
Asset           Size      Chunks            Chunk Namesmain.bundle.js  1.5 MiB    main  [emitted]  main

Our chat application's source code gets bundled into one bundle: main.bundle.js. A large bundle size can affect the loading time of our application significantly depending on the user's device and network connection. Before the App component is able to render its contents to the user's screen, it first has to load and parse all modules.

Luckily, there are many ways to speed up the loading time! We don't always have to import all modules at once: maybe there are some modules that should only get rendered based on user interaction, like the EmojiPicker in this case, or rendered further down the page. Instead of importing all component statically, we can dynamically import the modules after the App component has rendered its contents and the user is able to interact with our application.

Source

来源与署名

来源:patternsdev/skills位于javascript/static-import提交48bf58a

许可证: MIT

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架