Referencing an import dynamically

Asked

Viewed 73 times

1

Below I’m setting some Imports;

import users from './user';
import securities from './security';
import softwares from './software';

and I want to be able to access them in the course of my file, but I can only access them dynamically if I do this:

const allCollections = {
  users,
  securities,
  softwares
};

this way I can use the way I need:

function showImportDynamically(nameOfImportWanted) {
  console.log(allCollections[nameOfImportWanted]);
}

You can do that without having to resort to creating a Object() containing all? I tried to use global.users, but it didn’t work. I tried to look at the documentation so that if I did import './users' it remained in memory but I could not capture it. Below the file ./users as an example:

const users = {
  fields: {
    state: {},
    city: {},
    name: {}
  }
};

export default users;
  • @handoncloud works fine, but as I access it in function showImportDynamically(arg) without knowing which import I want to use? I’ll only know which import to use when passed by argument in the function

  • 1

    I think for what you want, this approach of using an object is the best output. Or you can use the require (instead of import), which takes a string as a parameter, thus allowing it to be set dynamically.

  • @mrlew, I’ll have to leave it so I’ve looked for other ways(using require would work the way I want), but I don’t want to let go of doing my whole ES6 project.

1 answer

0

I know almost nothing about the modules' syntax implemented in ES6, although it has an overview of how it works on that page (but usually the Mozilla documentation is wrong/incomplete in my opinion...).

In your attempt to use export default, it is possible to obtain the exported default value with this syntax (such as exemplified here):

import users from './users';

And if you are not using standard export:

import * as users from './users';

In Typescript this will move all exports of the requested module to an object-based value, accessible in a variable users (although I don’t know what kind of variable that would be).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.