ES6:使用命名空间导入特定值 [英] ES6: import specific values with namespace

查看:193
本文介绍了ES6:使用命名空间导入特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不时想做一件事,我无法弄清:

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

假设module1.js导出3个值:

//module1.js

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

然后,在module2.js中,我想将其中的两个导入到一个对象中(作为一种命名空间):

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 };

这可行,但是现在ac既存在于constants中,也直接存在于模块范围中.

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?

推荐答案

按照 MDN文档,您可以在整个模块内容(例如* as constants)或单个内容(例如b as constants)上设置别名.但是您不能在特定内容上设置别名.因此,解决方案之一就是使用*.

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';

另一种可能的解决方案是将{ a, c }作为默认值传递.

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);

这篇关于ES6:使用命名空间导入特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆