Arnav Borborah
Arnav Borborah

Reputation: 11769

Typescript compiler is not detecting a missing import for lodash with webpack

I'm trying to set up webpack with Typescript in my project using the official tutorial. Here is my folder structure and the important files:

├── dist
│   ├── bundle.js
│   └── index.html
├── package-lock.json
├── package.json
├── src
│   └── index.ts
├── tsconfig.json
└── webpack.config.js

src/index.ts:

// import _ from 'lodash';

const result = _.add(5, 6);
console.log(result);

webpack.config.js:

const path = require('path');

module.exports = {
  entry: './src/index.ts',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: [ '.tsx', '.ts', '.js' ],
  },
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
};

tsconfig.json:

{
    "compilerOptions": {
      "outDir": "./dist/",
      "noImplicitAny": true,
      "strict": true,
      "module": "es6",
      "target": "es5",
      "allowSyntheticDefaultImports": true
    }
  }

Notice that in index.ts that the import for lodash (I ran npm i lodash @types/lodash) is commented out. This should be a TS error, but this is what I see in VSCode:

No error for missing import

In addition, I am able to compile the project into a bundle by running npx webpack (tsc src/index.ts also works). However, when I open the file in the browser, I see this in the console:

Lodash underscore not found ReferenceError

Obviously, this shows that TS assumes _ is defined globally (not sure how) even though the package isn't actually imported itself. Uncommenting the import fixes the ReferenceError, but I don't understand why the Typescript Compiler doesn't realize that lodash isn't imported and report a compile error.

One thing I did notice though, is that when I changed my file to the following, I got this warning with a squiggly red line under the underscore for _.add:

// import _ from 'lodash';
import a from 'lodash';

const result = _.add(5, 6);
console.log(result);

'_' refers to a UMD global, but the current file is a module. Consider adding an import instead. ts(2686)

Upvotes: 0

Views: 1020

Answers (1)

Matt Bierner
Matt Bierner

Reputation: 65195

The lodash typings declare that a global variable _. This means that as long as those typings are included in your project, TypeScript will pick up the global definition of _.

Additionally, the reason why you see a warning when using _ is module files (files that use import or export) is that accessing global in modules is often unexpected. The best practice is to always use proper imports

Upvotes: 1

Related Questions