PierBJX
PierBJX

Reputation: 2353

Export several variables in one

In TS, I have Class1 from class.ts, some functions from helper.ts, some variables from variables.ts:

For example, variables.ts looks like that:

export const test1 = 'test1';
export const test2 = 0;
export const test3 = 'test3';
export const test4 = 'test4';

Then with Webpack, I give the api.ts like the entry to build a module.

api.ts

export { Class1 } from './class1';
export { helper1, helper2 } from './helper';
export * from './variables';

Like this, in my webapplication, in JS, I import what I need from this module. However, instead of importing each variables like this:

import { test1, test2, test3, test4 } from 'api';

I would like to know if it was possible to import something like this:

import { variables } from 'api';
test1 = variables.test1;

or something like :

import { variables.test1, variables.test3} from 'api';

What should I change in the TS to do that ?

Upvotes: 0

Views: 65

Answers (4)

David Alvarez
David Alvarez

Reputation: 1286

To complete Jack Bashfor answer, I would suggest export default

// variables.js
export default const variables = {
  test1: 'test1',
  test2: 0,
  test3: 'test3',
  test4: 'test4'
};


// file.js
import nameYouWant from 'variables'
consol.log(nameYouWant.test1);
// ...

Upvotes: 1

Paleo
Paleo

Reputation: 23682

I suggest to import all variables as a module namespace object, then to export the object:

import * as variables from './variables';
export { variables };

See also: "module namespace object" in this article from Mozilla.

Upvotes: 2

Fuu
Fuu

Reputation: 175

This is how RXJS solves this problem:

https://github.com/ReactiveX/rxjs/blob/master/src/internal/umd.ts

api.ts

export { Class1 } from './class1';
export { helper1, helper2 } from './helper';

import * as _variables from './variables';
export const variables = _variables;

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44087

Just use a wrapper object named variables:

export const variables = {
  test1: 'test1',
  test2: 0,
  test3: 'test3',
  test4: 'test4'
};

Upvotes: 2

Related Questions