能否使用EXPORT *导出ES6当前模块中的所有名称?
Great question! Let's clear this up right away: JavaScript's ES module syntax does not have a direct export * (without from) way to export all names from the current module out of the box. The export * from 'module' syntax is specifically for re-exporting all named exports from another module, not for dumping your current module's own variables, functions, or classes.
So what are the workarounds?
If you want to avoid adding export to every single declaration or listing them one by one repeatedly, here are your best options:
1. Bundle exports into a single object
You can wrap all the values you want to expose into an object, then export that object. This lets you import the whole bundle or destructure specific values later:
// Inside your module const appName = "MyApp"; function calculateTotal(items) { return items.reduce((a,b) => a + b, 0); } class User { constructor(name) { this.name = name; } } // Bundle everything into an exportable object export const moduleExports = { appName, calculateTotal, User };
Then to use it:
// Import the whole bundle import { moduleExports } from "./your-module.js"; console.log(moduleExports.appName); // Or destructure specific values import { moduleExports } from "./your-module.js"; const { calculateTotal, User } = moduleExports;
2. Explicit bulk export list
This is the most idiomatic ES module approach for exposing multiple values. Instead of adding export to each declaration, define all your code first, then list everything you want to export in one place:
// Inside your module (no `export` prefix here) const appName = "MyApp"; function calculateTotal(items) { return items.reduce((a,b) => a + b, 0); } class User { constructor(name) { this.name = name; } } // Explicitly list all names to export export { appName, calculateTotal, User };
This keeps your exports organized in one spot, and avoids accidentally exporting internal helper variables you don't want to expose (which a hypothetical "export all" syntax might do).
Why isn't there a native export * for current modules?
ES modules are designed around explicit exports to make code more maintainable and avoid accidental exposure of internal implementation details. A blanket "export everything" rule could leak helper functions, temporary variables, or other private logic that's only meant to be used inside the module.
内容的提问来源于stack exchange,提问作者Jacques de Hooge

