DEV Community

Alec Larson
Alec Larson

Posted on

Keep @types/node out of your React project

If you're trying to prevent @types/node (or any other global types package) from leaking into your React project, you will probably end up tinkering with your tsconfig.json and you'll eventually try disabling implicit type imports altogether like so:

{
  "include": ["src"],
  "compilerOptions": {
    "types": []
  }
}
Enter fullscreen mode Exit fullscreen mode

But first, why is @types/node leaking into your React components in the first place? Chances are that one of your dev dependencies (eg: @testing-library/react-native if you're writing a React Native app) relies on @types/node and so it ends up in your node_modules.

Normally, that won't be a problem after you put "types": [] in your tsconfig.json, but sometimes that doesn't work, and you commence pulling your hair out.

But then, in a stroke of genius, you decide to use the --traceResolution flag when compiling your project:

yarn tsc -p . --traceResolution --noEmit
Enter fullscreen mode Exit fullscreen mode

You scour its logs for the culprit, using cmd+f to save yourself some time. A-ha! Turns out a transient dependency (aka an indirect dependency) has a triple-slash directive in one of its ambient declarations (aka .d.ts modules). Behold!

/// <reference types="node" />
Enter fullscreen mode Exit fullscreen mode

You screech in terror!

Now there's only one thing to do. Open a PR and maintain a fork until the dreaded <reference> tag is obliterated from this Earth, never to return.

Top comments (0)