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.
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
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