xweb
xweb

Reputation: 123

How do I use Javascript ES6 ES2015 modules to export / import constants directly to the import module namespace?

OK, I can't quite find the answer to this. I am using webpack and babel es2015 preset to handle ES2015 modules.

Module 1 to export, filename "foobar.js"

export const FOO = 'foo'
export const BAR = 'bar'

Is there a way to import this constant into my global namespace in my import module?

I want to do this in my module that will use the constants:

import 'foobar'

const doSomething = () => { console.log(FOO + BAR) }

I know that this would work:

import * as CONSTANTS from 'foobar'

const doSomething = () => { console.log(CONSTANTS.FOO + CONSTANTS.BAR) }

...and that there are other ways to achieve the same result of the import being in a particular namespace. But I want to use the constants without a prefix.

Is there a way to directly import ALL the exports from a different module into the root namespace of the importing module?

*NOTE: I know that I can do this:

import {FOO, BAR} from 'foobar'

But then I have to explicitly reference each of the constants in the import, which leads to more headaches rather than less.

Upvotes: 9

Views: 11654

Answers (2)

samanime
samanime

Reputation: 26547

In addition to the two options you already referenced:

import * as CONSTANTS from 'foobar';
import { FOO, BAR } from 'foobar';

You can also do a default export to get them all, but it's functionally the same as option one:

// foobar.js
const FOO = 'foo';
const BAR = 'bar';

export default { FOO, BAR };

// myfile.js
import CONSTANTS from 'foobar';

The other method would be to dynamically populate them for either global or window (global for Node.js, window for browser code).

However, I highly recommend NOT using this method as you won't be able to use any help from your IDE, which will lead to lots of errors. Writing the extra code now is totally worth not having difficult-to-spot bugs later on.

import CONSTANTS from 'foobar';

Object.keys(CONSTANTS).forEach(key => window[key] = CONSTANTS[key]);

console.log(FOO, BAR);   

Example:

const CONSTANTS = { FOO: 'foo', BAR: 'bar' };

Object.keys(CONSTANTS).forEach(key => window[key] = CONSTANTS[key]);

console.log(FOO, BAR);

By putting them in the root level element, you can get away without having to implement them directly.

However, please don't use this method.

Upvotes: 8

intentionally-left-nil
intentionally-left-nil

Reputation: 8284

There's no way with ES2015 to wildcard import variables into the root namespace of a module.

Your two options are

import * as CONSTANTS from 'foobar'

or

import {FOO, BAR} from 'foobar'

sources:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

http://2ality.com/2014/09/es6-modules-final.html

Upvotes: 4

Related Questions