Ciwan Ciwan - 1 month ago 58
TypeScript Question

TypeScript D3 v4 import not working

I am trying to build a tiny JS library on top of D3 to draw a line chart. I am fairly new to the whole scene, but I thought I'd learn best by jumping in the "deep end".

Here is the content of my

package.json


{
"name": "d3play02",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"d3-array": "^1.0.1",
"d3-axis": "^1.0.3",
"d3-request": "^1.0.2",
"d3-scale": "^1.0.3",
"d3-selection": "^1.0.2",
"d3-shape": "^1.0.3",
"d3-time-format": "^2.0.2",
"rollup": "^0.36.3",
"rollup-plugin-node-resolve": "^2.0.0",
"uglify-js": "^2.7.4"
},
"dependencies": {
"@types/d3": "^4.2.37"
}
}


I have a file called
LineChart.ts
and in there I have:

/// <reference path="node_modules/@types/d3/node_modules/@types/d3-request/index.d.ts" />
import csv from 'd3-request';

class LineChart {
data(url: string): DsvRequest {
// code to go here
}
}


But this is giving me an error saying this

module error

It is complaining that it can't find the
d3-request
module, but I have that installed and based on the stuff I've read, I am importing correctly!

Any help would be greatly appreciated.

Answer

Your npm installs related to d3 should be as follows:

If you intend to use only a subset of the modules, for each module you need to install the module itself and the corresponding definition file.

E.g.: npm install d3-array --save and npm install @types/d3-array --save The actual d3-array module will be a proper dependency (not a devDependency as it appears in your snippet above). The definitions from @types may be --save or --save-dev that depends on your use case (for a library used by other code, a proper dependency should be used)

When you want to use the D3 modules with a module loader, you can then import standard TypeScript syntax:

import * as  d3Array from 'd3-array';
import {select, Selection} from 'd3-selection';

Or similar, depending on your needs.

For convenience you could create a simple "bundling" module so that you can access your custom bundle in a more consolidated form:

// d3-bundle.ts
export * from 'd3-array';
export * from 'd3-axis';
...
export * from 'd3-time-format';

You can tailor this module to your needs, including re-exporting only a subset of the members of the individual modules using export {...} from 'd3-MODULE';

In whatever module you want to use D3 now, you would import 'd3-bundle' using an appropriate relative path and you will have access to what you put through the bundle barrel:

// use-d3.ts
import { csv, DsvRequest } from './d3-bundle'; // again, use the right relative path for your project

class LineChart {
  data(url: string): DsvRequest {
      // code to go here
  }
}