'Can I export multiple named exports in a named set without affecting call to variable?

I have constants file with:

export const VAR1 = 'VAR1';
export const VAR2 = 'VAR2';
export const VAR3 = 'VAR3';
export const VAR4 = 'VAR4';
export const VAR5 = 'VAR5';
export const VAR6 = 'VAR6';
export const VAR7 = 'VAR7';
export const VAR8 = 'VAR8';
export const VAR9 = 'VAR9';
export const VAR10 = 'VAR10';

Some of the constants can be used separately and some I use as a specific set in several files, like:

import {VAR1, VAR2, VAR3, VAR8, VAR9, VAR10} from './constants'

Can I have several exports in a set, so that they can be easily imported in multiple files, but be called using same names? For example:

export set1 = [VAR1, VAR2, VAR3, VAR8, VAR9, VAR10];

And then in file:

import set1 from './constants';

if(input === VAR1) doSomething()

So I want to be able to import multiple named exports in one go, but still keep ability to simply call them just by their name.



Solution 1:[1]

You can do that, though your export and usage are incorrect, it would be (but keep reading):

export const VAR1 = "VAR1";
export const VAR2 = "VAR2";
// ...

export const set1 = [VAR1, VAR2, /*...*/];
// or probably more usefully, as an object:
export const set1 = {VAR1, VAR2, /*...*/};

Then the import and usage would be:

import { set1 } from "./constants";

// If you use an array:
if (input === set1[0]) doSomething();
// Or if you use an object:
if (input === set1.VAR1) doSomething();

Note that in both cases, there is no ongoing link between the exported VAR1 (etc.) and the exported set1. But since VAR1 and such are constants, that doesn't matter, their values never change. (It would matter if they weren't constants, because the set would only have their value as of when the export occurred, not their updated value later.)


Or using a default export (I don't like them, but some people do):

export const VAR1 = "VAR1";
export const VAR2 = "VAR2";
// ...

export default [VAR1, VAR2, /*...*/];
// or probably more usefully, as an object:
export default {VAR1, VAR2, /*...*/};

Then the import and usage would be:

import set1 from "./constants";

// If you use an array:
if (input === set1[0]) doSomething();
// Or if you use an object:
if (input === set1.VAR1) doSomething();

Or you could leave the exports alone and do a module namespace import:

import * as set1 from "./constants";

if (input === set1.VAR1) doSomething();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1