ES6模块对象/变量导入导出机制及重复导入实例化问题
Hey there! Let's tackle your ES6 module questions clearly and practically—no jargon overload, promise.
ES6 modules use a static, file-based system processed before your code runs (at compile time). Here’s the core breakdown:
Export types & matching imports
There are two main export styles, each paired with specific import syntax:
Default exports: Each module can have exactly one default export, perfect for when a module’s main purpose is exposing a single value (like a class, function, or object).
// Config.js export default class Config { constructor() { this.apiUrl = "https://api.example.com"; } }Import it with any name you want:
import MyConfig from './Config.js'; // Works even though the export is named "Config"Named exports: Use these to expose multiple related values from a module.
// Utils.js export const MAX_RETRIES = 3; export function formatDate(date) { return new Date(date).toLocaleDateString(); }Import them by their exact names (or rename with
asif needed):import { MAX_RETRIES, formatDate as format } from './Utils.js';
Key behavior for objects/variables
When you export a variable or object:
- The module runs once the first time it’s imported anywhere in your app.
- All exported values are stored in a module-level cache.
- Subsequent imports don’t re-run the module—they just reference the cached values.
This means every import gets the same reference to the exported object, not a fresh copy.
myConfig create a new Config instance every time? Short answer: No, it won’t. Here’s why:
First, let’s fix a tiny syntax quirk in your code—export myConfig; should be export { myConfig }; for a named export (or export default myConfig; for a default export):
// myConfig.js import Config from './Config.js'; const myConfig = new Config(); export { myConfig }; // Corrected named export
When the first file imports myConfig.js:
- The module executes: it imports
Config, creates a singlemyConfiginstance, and exports that instance. - The entire module and its exported values are cached by the JavaScript engine.
Every subsequent import (from other files) skips re-running the module. Instead, it pulls the already-created myConfig instance from the cache. So every file that imports myConfig gets the exact same instance—no new Config objects are created.
If you wanted a fresh instance every time, you’d export a function that creates the instance instead:
// myConfig.js import Config from './Config.js'; export function createConfig() { return new Config(); }
Then each import can call createConfig() to get a new instance whenever needed.
内容的提问来源于stack exchange,提问作者AKK9

