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.
相关问题
- Angular RxJS mergeMap types
- void before promise syntax
- Ignore Typescript errors in Webpack-dev-server
- Highlight parent path to the root
- Angular: ngc or tsc?
相关文章
- Cannot find module 'redux' 怎么解决?
- How to get a Component's own ElementRef for re
- 'Pick' only refers to a type, but is being
- Why does `keyof any` have type of `string | number
- React testing library: Test attribute / prop
- TypeScript - Puppeteer library error: “Cannot find
- How to reference type of self in Typescript interf
- React and typescript with webpack typing issue
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 used3
as a global namespace without having animport
orrequire
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:Now you can refer to
d3
from modules without importing from"d3"
, and you should still get all the correct type checking on thed3
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.