CSSer
CSSer

Reputation: 2587

Javascript: import one and the rest?

For object const a = {b: 1, c: 2, d: 3}, we can do destructuring like this: const {b, ...rest} = a.

I'm wondering if it's also possible for imports.

Say I have a file file1.js:

// file1.js
export const a = 1;
export const b = 2;
export const c = 3;

Can I import from this file by importing one and the rest like destructuring?

// file2.js
import {a, ...rest} from "file1";

Upvotes: 9

Views: 1441

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074138

Not directly, there's no import form for it.

What you can do instead is import the module's module namespace object, then use destructuring on it:

import * as file1 from "file1";
const {a, ...rest} = file1;

FWIW, the specification has an example list of import forms here. It doesn't show what you can and can't combine, but those are the basic forms.

Upvotes: 7

Related Questions