ES6: import specific values with namespace

2019-03-02 12:59发布

问题:

There is a specific thing i want to do from time to time, that i cannot figure out:

suppose module1.js exports 3 values:

//module1.js

export const a = 'a';
export const b = 'b';
export const c = 'c';

And then, in module2.js, I want to import two of these, into an object (as a kind of namespace thing):

//module2.js

import { a, c } as constants from './module1'; //<-WRONG!

So what I end up doing is something like this:

//module2.js

import { a, c } from './module1';
const constants = { a, c };

This works, but now a and c exist both in constants and also directly in the module scope.

Is there a way to avoid this?

回答1:

As per MDN documentation, you can either set an alias on entire module contents such as * as constants or a single content such as b as constants. But you can't set an alias on specific contents. So one of the solutions would be using *.

import * as constants from './module1';

Another possible solution would be passing { a, c } as default.

//module1.js

export const a = ...
export const b = ...
export const c = ...
export const d = ...
export default { a, b, c };

/module2.js
import contants from './someModule';
doStuff(constatns);

Lastly, If you don't want to pass these constants as default, you can create an object and pass that object.

//module1.js

export const a = ...
export const b = ...
export const c = ...
export const b = ...
export const myCustomConstants = { a, c };

//module2.js
import { myCustomConstants } from './someModule';
doStuff(myCustomConstants);


回答2:

Do you mean something like

import * as constants from './module1';

You could also remove some if you need to pass them down, something like lodash pick

const cleanConstants = _.pick(['a', 'c'], constants);