Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import into object?

Tags:

ecmascript-6

Let's start with an example:

import renewCreepLife from '../tasks/renew_creep_life';
import harvestEnergy from '../tasks/harvest_energy';
import pickupEnergy from '../tasks/pickup_energy';
import storeEnergy from '../tasks/store_energy';
import upgradeController from '../tasks/upgrade_controller';

const taskFuncs = {
    [Tasks.RENEW]: renewCreepLife,
    [Tasks.PICKUP_ENERGY]: pickupEnergy,
    [Tasks.HARVESTING]: harvestEnergy,
    [Tasks.STORING]: storeEnergy,
    [Tasks.UPGRADING]: upgradeController,
};

Is there any way to simplify this so that I'm not creating these pointless temporary variable names? Something like:

// incorrect but desired syntax
const taskFuncs = {
    [Tasks.RENEW]: import '../tasks/renew_creep_life',
};

N.B. each of those files is using export default function()

like image 454
mpen Avatar asked Apr 19 '16 05:04

mpen


People also ask

How do I import an object into node js?

You can define your array on the exports object in order to allow to import it. You could create a . json file as well, if your array only contains simple objects. If you require a module (for the first time), its code is executed and the exports object is returned and cached.

Can I use import in JavaScript?

Introduction to the JavaScript import()The import() allows you to dynamically import a module when needed. Here is how the import() works: The import() accepts a module specifier ( moduleSpecifier ) that has the same format as the module specifier used for the import statement.


1 Answers

No. The import statement does not have a return value, so it can never be used to assign directly to a variable like that.

Additionally, import and export must be declared at the top level.

This is not possible with ES6 and likely will stay that way for the foreseeable future (ES2016+).

However, there is a HTML Module Loader spec being worked on which will allow you to load modules like:

System.import('../tasks/renew_creep_life')
.then(renewCreepLife => {

});

But since it's promise-based, you'll still not be able to just write it inline in an object like that.

If you want synchronous loading, NodeJS' require is probably the closest you'll get. There are browser implementations such as Webpack/Browserify/etc. which attempt to mimic the behaviour:

const taskFuncs = {
    [Tasks.RENEW]: require('../tasks/renew_creep_life').default
};
like image 96
CodingIntrigue Avatar answered Oct 08 '22 00:10

CodingIntrigue