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()
)?
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.
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.
There are two types of module imports: Named Imports. Default Imports.
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.
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()...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With