The Daily TIL

August 11, 2019 by AndyAndyvscodeeslintdebuggingjavascript

The Danger of Accidental Imports

Sometimes, some of the more “helpful” features of our code editors and IDEs can cause annoying problems.

But there are a few things you can do to make these problems easier to prevent or debug.

Example

The example I ran into today is unwanted auto-import of dependencies.

I was minding my own business, writing a React component in VSCode, when I started to randomly see this error message in Chrome.

weird error message

I don’t remember making any changes to NPM dependency versions, adding any new files, changing any build config, etc…

My first instinct was to search for the error message, and there was really only one instance of its occurrence.

I also saw node-gyp in the stacktrace, and wondered if there was a problem with some bindings in node_modules. But before diving down that rabbit hole, I decided to do a quick diff to sanity check what I thought were some pretty simple changes. I found this:

the cause

It looked like I had somehow added an import of what was clearly an unwanted dependency, import { NoEmitOnErrorsPlugin } from 'webpack';. Made sense that importing and loading a webpack dev dependency (with some system bindings) in my application wouldn’t work very well.

So I removed it and all clear.

I had obviously accidentally told VSCode to import this dependency. I wanted to prevent this from happening again, so I decided to turn on a lint rule that would yell at me when I had a dependency that I had imported but not actually used (a good indicator that it doesn’t belong there).

I’m using eslint-loader as part of my Webpack config, so as long as I have a rule for catching things I’m not using, eslint-loader will show me these errors in a pretty obvious way while I’m writing my code.

I added this rule to my .eslintrc.

"rules": {
  "@typescript-eslint/no-unused-vars": ["error"],
}

The resulting error is WAY more helpful:

the actual root cause

To recap, the 2 useful things I did here were:

  1. always run a quick git diff when something randomly starts breaking.
  2. there’s probably a lint rule that can prevent you from making hard-to-debug mistakes in the future.

References