繁体   English   中英

我可以从 JS 中的另一个文件中逐个导入特定变量吗?

[英]Can I import specific variable by variable from another file in JS?

我想从另一个 Javascript 文件中导入一个特定的变量。 我现在以标准方式执行此操作。

例如,我有一个validation.js文件,其中包含以下代码:

export const profile = {...}

我的问题是我想通过变量名从另一个文件导入这个变量:

import {profile} from "validation" //this will work

但是这个

let action = 'profile';

import {action} from "validation" // this will surely look for action in validation.js and not profile.

如何使用action字符串导入正确的变量?

而是导入整个命名空间,其中包含命名导出作为对象的属性,然后您可以使用[]访问对象上的适当属性:

import * as validation from "validation";
// ...
const action = 'profile';
const profile = validation[action];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM