22

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/

Mourndark
  • 2,526
  • 5
  • 28
  • 52

1 Answers1

27

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>
thibautg
  • 2,004
  • 1
  • 14
  • 17
  • Seems quite redundant. You should be able to import the same "assets" directly in your component file. There's no functional difference there. – Paul-Sebastian Manole Jun 11 '20 at 11:23
  • 5
    That's true. Here the goal is to cherry-pick the d3 modules in a central location, and then import them all in the components and use them with the `d3.` prefix. – thibautg Jun 20 '20 at 10:30