如何将解构导入的指定模块成员整合为单个对象?
First off, let's break down why your attempted syntax throws an error:
JavaScript's ES module import syntax doesn't support using as to bundle destructured named exports directly into a new object. The as keyword only works for two cases:
- Renaming a single export (e.g.,
import { A as filterA } from '@/helpers/filters') - Importing the entire module as a namespace object (e.g.,
import * as allFilters from '@/helpers/filters')
So your line import { A, B, C } as filters from '@/helpers/filters' violates the syntax rules, hence the "Expression statement is not assignment or call" error.
Solution 1: Your Original (and Most Readable) Approach
Your initial two-line code is already clean and easy to understand—this is the most recommended approach for balance of brevity and readability:
import { A, B, C } from '@/helpers/filters'; const filters = { A, B, C };
Solution 2: Namespace Import + Object Destructuring
If you want to condense things a bit more, you can import the full module namespace first, then extract and bundle the functions you need:
import * as allFilters from '@/helpers/filters'; const filters = { A: allFilters.A, B: allFilters.B, C: allFilters.C };
Or use object destructuring to make it even cleaner:
import * as allFilters from '@/helpers/filters'; const { A, B, C } = allFilters; const filters = { A, B, C };
Solution 3: One-Liner with Dynamic Import (Async Context Only)
For a true one-liner, you can use dynamic import() combined with an IIFE (Immediately Invoked Function Expression)—just note this requires an async context:
const filters = (({ A, B, C }) => ({ A, B, C }))(await import('@/helpers/filters'));
Or handle the promise explicitly if you can't use await:
import('@/helpers/filters').then(({ A, B, C }) => { const filters = { A, B, C }; // Your logic here });
At the end of the day, your original approach is the best choice for most cases—it's straightforward and doesn't sacrifice readability for the sake of brevity.
内容的提问来源于stack exchange,提问作者van_folmert

