Module Importer (import-module.js)
Examine the dynamic module loader, require cache-busters, and ESM vs CommonJS import wrappers.
Key File Location: ./dinou/core/import-module.js💡 Overview
In development environments, when a developer modifies a page or component, the server must reload the code immediately. Node.js, however, caches loaded modules in memory. Subsequent imports return the cached code, ignoring file changes.
The import-module.js utility resolves this restriction. It implements dynamic cache-busting logic for both standard ES modules and CommonJS structures.
📊 Module Import Flow
The flowchart below shows how modules are imported based on the bundler type and environment state:
⚡ Dynamic Cache-Busting
The utility handles cache clearing using two techniques:
- CommonJS require.cache: If running Webpack in development, queries
require.resolve(path)and deletes the matched entry fromrequire.cache, forcing Node to reread the file. - ESM query timestamping: Node's native
import()cache cannot be deleted. The importer bypasses this by appending a dynamic timestamp query parameter (?t=[timestamp]) to the file URL. Node treats this as a new module URL, bypassing the cache.
⚙️ Complete Code Walkthrough
Below is the full, complete code of import-module.js:
const { pathToFileURL } = require("url");
const path = require("path");
const isWebpack = process.env.DINOU_BUILD_TOOL === "webpack";
async function importModule(modulePath) {
const absPath = path.isAbsolute(modulePath)
? modulePath
: path.resolve(process.cwd(), modulePath);
// 1. ESM Mode: Node.js standard imports
if (!isWebpack) {
let fileUrl = pathToFileURL(absPath).href;
if (process.env.NODE_ENV !== "production") {
// Append current timestamp query parameter to bust Node's ESM cache
fileUrl += `?t=${Date.now()}`;
}
const mod = await import(fileUrl);
return mod;
}
// 2. Webpack Mode: CommonJS require loops
try {
if (process.env.NODE_ENV !== "production") {
try {
const resolved = require.resolve(absPath);
delete require.cache[resolved]; // Prune cache to load updated code
} catch (e) {}
}
return require(absPath);
} catch (err) {
// 3. Fallback: If require fails with ESM module error, import dynamically
if (
err.code === "ERR_REQUIRE_ESM" ||
/require\(\)/.test(err.message)
) {
let fileUrl = pathToFileURL(absPath).href;
if (process.env.NODE_ENV !== "production") {
fileUrl += `?t=${Date.now()}`;
}
const mod = await import(fileUrl);
return mod;
}
throw err;
}
}
module.exports = importModule;