Matching typescript definition module declaration to node module importing

563 Views Asked by At

I have installed the popular d3 library through NPM.

npm install d3
tsd install d3 -save
tsc

In my home.ts file, I have imported the module:

import * as d3 from 'd3/d3';

This compiles correctly, but I get this semantic error:

app/home/components/home.ts(2,21): error TS2307: Cannot find module 'd3/d3'.

Also, I lose all of my syntax highlighting/type-ahead info in my IDE.

The original d3.d.ts file provided by TSD declares the module like so:

declare module 'd3' {
    export = d3;
}

If I change the module to 'd3/d3', everything works fine:

declare module 'd3/d3' {
    export = d3;
}

So, I'm having a hard time getting both of what I need:

import * as d3 from 'd3'; gives me the type definitions I expect, but looks for a module in node_modules/d3.js which is incorrect.

import * as d3 from 'd3/d3'; finds the correct module because the path is right, but i lose my type definitions because the module declaration doesn't match.

How can I get these two things to match up so I can simply import the module without losing my type definitions?

FYI: I am using typescript 1.7.5, and my moduleResolution is set to node.

1

There are 1 best solutions below

0
On

You need to tell the loader where to look for things. In your systemjs.config.js, add the following mapping in the map object:

var map= {
...
...
'd3':  'node_modules/d3'
};

The d3.js file is indeed located in node_modules/d3 and the above mapping will let the loader find the file. Now, you can import it in your components as:

import * as d3 from 'd3';