jefelewis
jefelewis

Reputation: 2059

Export all constants from files into index.ts and then export those constants as keys of an object?

I have a constant library that has many files such as the following structure:

#1 index.ts

#2 src/

Is it possible to import and export all of the constants from each file into index.ts such that I can import into a project such as the following:

// Imports: Constants
import { constants } from '@jeff/constants-library';

console.log(constants.contact.first);
console.log(constants.contact.second);
console.log(constants.contact.third);

What is the fastest/most efficient way to dynamically export the constants from my library files so I can import the into my projects?

Upvotes: 2

Views: 4580

Answers (1)

Jeff Bowman
Jeff Bowman

Reputation: 95704

In your files like contact and location, you'll need to mark the const values you want as exports. Modules are designed for encapsulation, so dynamic export isn't really an option here. However, it's just a matter of adding the keyword export:

export const first = [];

After that, you can create a constants-library.ts or constants-library/index.ts which automatically exports and imports:

import * as foo from './foo';
import * as bar from './bar';

export const constants = { foo, bar };

At this point, assuming your @jeff path is set up, your code should work as expected:

import { constants } from '@jeff/constants-library';

console.log(constants.contact.first);

Note that this will include all of the exports in your files, since TypeScript can't tell which constants you want or didn't want--it only knows which exports you've listed. As an alternative, rather than exporting all of your consts individually, you could bundle them into a single export using object shorthand.

// in contact.ts and location.ts
export constants = { first, second, third };

// in constant-library.ts or constant-library/index.ts
import { constants as contact } from './contact';
import { constants as location } from './location';

export constants = { contact, location };
 

Upvotes: 1

Related Questions