4

I want to import a specific variable from another Javascript file. I now do this the standard way.

For example, I have a validation.js file where I have the following code:

export const profile = {...}

My problem is that I want to import this variable from another file by variable name:

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

But this

let action = 'profile';

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

How can I import the right variable by using the action string?

1 Answer 1

6

Import the whole namespace instead, which contains the named exports as properties of the object, and then you can just access the appropriate property on the object with []s:

import * as validation from "validation";
// ...
const action = 'profile';
const profile = validation[action];
Sign up to request clarification or add additional context in comments.

7 Comments

Well I know that I can import the whole namespace, but I was more interested if there was a way to import only that object by variable name.
Is there a reason you don't want to import the namespace? It's by far the easiest (and probably only good) method for doing something like this.
Well if my original validation file is huge it might cause performance issues.
The whole namespace will necessarily be loaded into memory regardless of whether you use a named import or whether you import the namespace, if that's what you're worried about - and if you want to be able to dynamically access a property on the namespace, having the whole namespace available to look at is the only real way of being able to achieve that, right? (unless you have the capability of refactoring the module that exports it, so that it only loads pieces at a time, or something like that)
The entire module's code will run regardless of if it's imported once, or many times, or via named imports, or via a namespace import. The purpose of having a namespace vs a standalone named import is for code organization, not for performance differences
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.