In the previous Command Configuration chapter, we created the "ID card" for our command. We registered the name stats so the application knows it exists.
However, we briefly glossed over one specific line in that configuration: the load function. In this chapter, we will explain exactly why we wrote it that way and how it makes our application incredibly fast.
To understand Lazy Loading, let's use a hiking analogy.
Imagine you are going on a hike (starting the application). You have a backpack.
In programming:
stats when the user actually types stats.We implement this "magic finger snap" using a JavaScript feature called Dynamic Import.
If we write our code like this, the file stats.js is loaded immediately when the app starts:
// โ This runs immediately!
import heavyLogic from './stats.js'
const config = {
name: 'stats',
// ...
}
Why this is bad: If you have 50 commands, the app has to load 50 files just to start, even if the user only wants to use one.
Instead, we wrap the import inside a function. This acts like a gate.
// โ
The file is NOT loaded yet
const config = {
name: 'stats',
// We define a function, but we don't call it
load: () => import('./stats.js'),
}
Why this works:
() => ...import(...).How does the main application use this mechanism? It waits for the user to trigger the command.
Here is the sequence of events:
stats.load() function.stats.js from the disk.Let's peek at how the main application (the "runner") handles this. While you don't need to write this part, understanding it helps you write better commands.
The runner uses the keywords async and await. Because loading a file takes a few milliseconds (or longer), the application pauses execution of that specific task until the file arrives.
Here is a simplified version of what the core system does when a user presses Enter:
async function runCommand(commandConfig) {
console.log("User requested: " + commandConfig.name)
// 1. Call the lazy loader
// 'await' means: "Pause here until the file is ready"
const module = await commandConfig.load()
// 2. The file is loaded! Now we run the default export
// We will learn about this export in the next chapter
module.default()
}
Explanation:
await commandConfig.load(): This triggers the arrow function we wrote in index.ts.const module: This variable now holds the contents of stats.js.module.default(): This runs the main function inside that file.In this chapter, we learned:
import()) wrapped in a function to achieve this.
Now that we have successfully loaded our command file (stats.js), what goes inside it? We configured our command as type: 'local-jsx', which means we are building a user interface.
Let's move on to writing that interface.
Next Chapter: Local JSX Command Handler
Generated by Code IQ