Giovanni Azua Giovanni Azua - 4 years ago 159
TypeScript Question

How to call javascript libraries from Typescript project?

I'm working on an existing Typescript AngularJS project. Now I'd like to use d3js but to do so I need to manually download the d3js typescript (turns out d3 is made of a million files) and then the d3js min javascript. The corporate proxy doesn't allow me to use tools to download/manage dependencies etc so I only have the manual option.

Therefore I prefer to simply import the d3js in the

index.html
and invoke d3js directly from Typescript without using the d3 ts version.

So I do e.g.

var svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 30, left: 40},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var x = d3.scaleBand()
.rangeRound([0, width])
.paddingInner(0.05)
.align(0.1);


but then I get the compiler errors "Cannot find name
d3
" is there a way to tell in Typescript that this Javascript object is defined elsewhere and it should not assume anything about it?

It is a pity that d3 js is split in a million pieces ... I find that it is not very useful, who will ever use d3
scale
without
select
? this makes no sense to me.

Answer Source

The definition file is only needed for compiling the ts source to js, it's not needed in order to run the js.

It will be the easiest to use it with @types:

npm install --save @types/d3

If you can't do that, then download the definition file manually and place it near your source and then reference it:

/// <reference path="PATH_TO_D3_D_TS" />

If you can't do that as well then declare it:

declare const d3: any;

That will tell the compiler that the variable d3 exists, and it's of type any, so you should not get exceptions from using it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download