Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct Way to Import D3.js into an Angular 2 Application

There are a lot of discrepancies on the correct way to import and use D3 in an Angular 2.0.0-rc.4 application. I have seen:

1) To be added to the root index.html file:

<script src="https://d3js.org/d3.v4.min.js"></script>

Then using:

Import * as d3 from 'd3';

in any component file that I want to implement a D3 visual in.

2) Using npm:

npm install d3 --save
typings install d3 --save

Then still using:

Import * as d3 from 'd3';

Though with TypeScript 2.0.0 Beta (if I am reading the documentation right) I can do:

npm install --save @types/d3

Then really use:

Import * as d3 from 'd3';

-- With both ways, adding the following to the var map = { } to the systemjs.config.js

'd3':'node_modules/d3/d3.min.js'

and adding to the var packages = { }

'd3':{main:'build/d3.js',defaultExtension:'js'}

Can anyone confirm the correct way to implement D3? Thank you.

like image 933
ntdog22 Avatar asked Jul 12 '16 17:07

ntdog22


1 Answers

The only way that works for me is to create a file "custom-d3.ts", inside I export what I need (for example):

export * from 'd3-axis';
export * from 'd3-format';
export * from 'd3-interpolate';
export * from 'd3-scale';
export * from 'd3-selection';
export * from 'd3-shape';

And then in my other ts files I can import d3 as: import * as d3 from '.../../custom-d3.ts'.

I get auto completion by installing the typings @types/d3, and no error with typescript.

You can also use this library that does all of that for you and is injectable in your classes: https://github.com/tomwanzek/d3-ng2-service

like image 71
Olivier Avatar answered Sep 28 '22 23:09

Olivier