I'm trying to use a number of d3 packages in a Vue.js project with NPM for package management. I was trying to make a fiddle of a problem I'm having but am unable to replicate the issue there - the code works exactly as it should do.
I'm trying to identify differences between the code running in JSFiddle and the code running in my app and (aside from obvious fact that I'm not running Vue.js in the fiddle) the big one is how I'm importing my extra libraries. In the fiddle I'm adding links to the relevant libraries from CDNJS while in my app I'm using NPM and import
. This is all to run charts using dc
, which builds on a lot of d3
features. My complete imports for the chart component is:
import dc from 'dc'
import crossfilter from 'crossfilter2'
import * as time from 'd3-time'
import * as scale from 'd3-scale'
I'm not using any features from the base d3
module.
The fiddle in question is here: https://jsfiddle.net/y1qby1xc/10/
Install D3 by running npm install d3 --save . Import D3 to App. js by adding import * as d3 from d3 . You need to use import * (“import everything”) since D3 has no default exported module.
Cases where it is necessary to use both “require” and “import” in a single file, are quite rare and it is generally not recommended and considered not a good practice. However, sometimes it is the easiest way for us to solve a problem. There are always trade-offs and the decision is up to you.
One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. To use the require() statement, a module must be saved with . js extension as opposed to .
Importing can be done in various ways:Node js doesn't support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error.
I am now using the following structure in my Vue projects. I am making a separate file to import all the needed modules and to export them all at once.
In ./src/assets/d3/index.js
:
import { select, selectAll } from 'd3-selection';
import {
scaleLinear,
scaleTime,
scaleOrdinal,
schemeCategory10,
} from 'd3-scale';
import { axisTop } from 'd3-axis';
export default {
select,
selectAll,
scaleLinear,
scaleTime,
scaleOrdinal,
schemeCategory10,
axisTop,
};
Then I import everything into my component and I am able to use all functions with their d3
prefix: d3.select
, d3.selectAll
etc.
In ./src/components/MyComponent.vue
:
<template>
</template>
<script>
import d3 from '@/assets/d3';
export default {
data() {
return {
};
},
};
</script>
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