简体   繁体   中英

Typescript and d3

I have an app that uses the d3 library. In typescript code, in order to use d3 successfully (ie, without compiler error TS2686, d3 refers to a UMD global, but the current file is a module), I have to include the line: import * as d3 from 'd3'; Problem with that is that it emits: require('d3'); in the JavaScript. That's not where the d3 library is in our application. It's under the root of the web app, in a directory called 'd3'. Also, I don't need it in the JavaScript at all because our index.html loads it as a global. Having a hard time figuring out how to get the TypeScript source to allow me to reference d3 without the import.

Currently UMD typedefs can't be referenced as a global namespace from within a module file. (It only allows you to reference a global namespace from a non-module file.) The workaround is to manually declare a global namespace within your project:

// global.d.ts
import * as _d3 from "d3";

declare global {
  const d3: typeof _d3;
}

Now you can refer to d3 from modules without importing from "d3" , and you should still get all the correct type checking on the d3 object based on @types/d3 .

The above answer by Aaron Beall is perfect for the very specific situation op is in, but more generally, if you want to use TypeScript with D3 these days, DefinitelyTyped is the way to go. You can just

npm i d3
npm i -D @types/d3

and

import * as d3 from 'd3';

like with any other @types library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM