Summary: It is recommended to install d3.js via npm along with the typings. The accepted answer provides more details on this issue. This question was asked during my initial stages of learning Angular. The npm
process is commonly used for tree-shaking, package management, and updating libraries.
I am working on an Angular 2 project (specifically the Quick Start project) where I am using d3.js version 4. Since there are no TypeScript definitions available for d3, which is a JavaScript library, I include it in the index.html file as follows:
<script src="https://d3js.org/d3.v4.min.js"></script>
In the typescript app.component.ts file, I use the d3.select() method to draw a circle, and it functions correctly:
d3.select("body").append("svg").attr("width", 50).attr("height", 50).append("circle").attr("cx", 25).attr("cy", 25).attr("r", 25).style("fill", "purple");
However, Visual Studio Code does not recognize d3 initially. After installing the typings from DefinitelyTyped using the command below, the IDE identifies d3 and offers code completion:
typings install dt~d3 --save --global
In another project attempt, I chose the npm
approach by running npm install --save d3
. By referencing the d3.js file from the node_modules folder in index.html like this,
<script src="node_modules/d3/build/d3.min.js"></script>
However, I questioned the need for using npm in this scenario since I do not utilize import statements for d3 in the component.ts files. Despite that, the application works fine without any issues. Am I overlooking something important here?