Referencing a import dynamically

1

Below I'm defining some imports;

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

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 it the way I need it:

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

Can you do this without resorting to creating a Object() containing all? I tried using global.users, but it did not work. I tried to take a look at the documentation so if I did import './users' it would stay in memory but I could not capture it. Below the ./users file as an example:

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

export default users;
    
asked by anonymous 12.02.2017 / 00:12

1 answer

0

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

In your attempt to use export default , you can get the default value exported with this syntax (such as sample here ):

import users from './users';

And if you're not using default export:

import * as users from './users';

In TypeScript this will move all exports of the required module into an object-based value accessible in a users variable (although I do not know what kind of variable this would be).

    
12.02.2017 / 15:02