Typescript and d3

2020-06-03 06:54发布

I have an app that uses the d3 library. In typescript code, in order to use d3 successfully (i.e., 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.

1条回答
够拽才男人
2楼-- · 2020-06-03 07:00

You have two possible options:

Suppress the warning

As of TypeScript 3.5 a --allowUmdGlobalAccess flag was added to allow you to access global definitions from module files. In your case this will mean you can use d3 as a global namespace without having an import or require statement. This will obviously apply to all module files in your project and for any other UMD type definitions (like React, for example) so just be aware that it may not be correct in all contexts, depending on your code setup and libraries in use.

Declare a global namespace

Previously to TS 3.5 and without the --allowUmdGlobalAccess flag 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.) This is an intentional safe-guard against accidentally referring to a global namespace that is not available in a strictly module-based project. 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.

This has the advantage over --allowUmdGlobalAccess in that it's very explicit about your particular code setup. In other words it won't inadvertently let you compile other UMD modules that your code setup is not providing globally.

查看更多
登录 后发表回答