Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to merge or nest ES6 imports?

Many modern JavaScript libraries are updating from monoliths to modularized npm packages; a couple of examples are lodash and d3.

This is great in terms of keeping build sizes down, but makes for a bit of awkwardness with imports. When loading the entire library, I write:

import d3 from 'd3';

let csv = d3.csv()...
let xScale = d3.scale()...

When loading individual modules instead of the whole package, I write:

import d3_scale from 'd3-scale';
import d3_request from 'd3-request';

let csv = d3_request.csv()...
let xScale = d3.scale.scaleLinear()...

Is there a syntax that would allow me to merge my imports so I can make all the function calls from each package off of a single object (e.g. d3.csv(), d3.scaleLinear())?

like image 312
ericsoco Avatar asked May 16 '16 04:05

ericsoco


People also ask

Does ES6 support import?

ES6 modules are automatically strict-mode code, even if you don't write "use strict"; in them. You can use import and export in modules.

What is ES6 import?

With the help of ES6, we can create modules in JavaScript. In a module, there can be classes, functions, variables, and objects as well. To make all these available in another file, we can use export and import. The export and import are the keywords used for exporting and importing one or more members in a module.

How many ways we can import a module in JS?

There are two types of module imports: Named Imports. Default Imports.

How many parts are there in ES6 module?

The ES6 module standard has two parts: Declarative syntax (for importing and exporting) Programmatic loader API: to configure how modules are loaded and to conditionally load modules.


1 Answers

As I was writing the question I figured out the answer. Self-rubber-ducking.

The spread operator looks pretty decent here:

import * as d3_request from 'd3-request';
import * as d3_scale from 'd3-scale';
const d3 = {
    ...d3_request,
    ...d3_scale
};

d3.csv('path/to.csv', (error, data) => {
    let xScale = d3.scale()...
});
like image 197
ericsoco Avatar answered Sep 22 '22 03:09

ericsoco