gpt4 book ai didi

ecmascript-6 - ES6 : import specific values with namespace

转载 作者:行者123 更新时间:2023-12-04 23:37:33 24 4
gpt4 key购买 nike

我不时想做一件具体的事情,但我无法弄清楚:

假设 module1.js导出 3 个值:

//module1.js

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

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

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

所以我最终做的是这样的:
//module2.js

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

这可行,但现在 ac两者都存在于 constants也直接在模块范围内。

有没有办法避免这种情况?

最佳答案

根据 MDN documentation ,您可以为整个模块内容设置别名,例如 * as constants或单个内容,例如 b as constants .但是您不能为特定内容设置别名。因此,其中一种解决方案是使用 *.

import * as constants from './module1';

另一种可能的解决方案是通过 { a, c }默认。
//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);

最后,如果您不想将这些常量作为默认值传递,您可以创建一个对象并传递该对象。
//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);

关于ecmascript-6 - ES6 : import specific values with namespace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48935969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com