The Typescript compiler is failing to catch a missing import for lodash when using webpack

Currently in the process of setting up webpack with Typescript for my project using resources from the official tutorial. Below is an overview of my folder structure and key 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
    }
  }

One observation made in index.ts is that the lodash import is commented out after running npm i lodash @types/lodash. Surprisingly, there isn't a TypeScript error flagged, as depicted below:

https://i.sstatic.net/EPPfA.png

Moreover, compiling the project into a bundle using npx webpack (tsc src/index.ts also works). However, upon browser inspection, the following console message appears:

https://i.sstatic.net/zplsR.png

Evidently, TypeScript wrongly assumes that _ is globally defined (unknown how), despite the absence of an actual import. Uncommenting the import resolves the ReferenceError, yet it remains unclear why the TypeScript Compiler fails to catch this issue.

An interesting discovery was switching the file content to the following, triggering a warning with red squiggly lines under _.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)

Answer №1

The lodash typings indicate a global variable _. Therefore, once these typings are included in your project, TypeScript will recognize the global definition of _.

Furthermore, the warning you receive when using _ in module files (files that use import or export) is due to the fact that accessing globals in modules can lead to unexpected behavior. It is recommended to always use appropriate imports.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to determine if two distinct selectors are targeting the same element on a webpage?

Consider the webpage shown below <div id="something"> <div id="selected"> </div> </div> Within playwright, I am using two selectors as follows.. selectorA = "#something >> div >> nth=1&q ...

I'm struggling to include a link in my project card component - I've tried using both the Link tag and anchor tag, but so far, I haven't been successful in

I am having trouble getting the link tag to work properly in my UI. I have tried using both the link and anchor tags, but neither seems to be functioning as expected. Can someone please advise on how to fix this issue? https://i.sstatic.net/tAD7C.png I w ...

Chaining Assignments in TypeScript

let a: { m?: string }; let b = a = {}; b.m = ''; // Property 'm' does not exist on type '{}'. let a: { m?: string } = {}; let b = a; b.m = ''; // It's OK Link to TypeScript Playground What occurs ...

What is the best way to pass a form result from a parent component to a child component

In the setup, there is a child component containing a form with various options for selection. The goal is to capture the user's selection and process it within this child component. Despite attempting to utilize an event in the parent component, the ...

Cannot assign argument of type 'string | undefined' to parameter expecting type 'string'. Typescript is being strict

While attempting to update an object using the SDK and having 'strict' mode enabled in typescript, I encountered the following error: const offer = client.offer(oldOfferDefinition!.id); await offer.replace(newOfferDefinition); error TS2345: Argu ...

Disabling eqeqeq for create-react-app with TypeScript: A step-by-step guide

I've exhaustively attempted various methods, but I can't seem to figure out how to disable eqeqeq for my specific project. The framework of my project is based on create-react-app using TypeScript. Here are some visual references: https://i.ss ...

Can we create a generic constraint that utilizes an index, be it a type or an object?

I am currently generating client models (Entities) along with their corresponding Primary Keys. My goal is to create a method signature where, based on the Entity provided, the second parameter should be its Primary Key only. The specific use of types an ...

What is the best way to input variables specified in script setup for conducting unit tests?

In my component, I am utilizing a reactive state that is defined within the script setup section: const state = reactive({ hello: 'world' }) This state can be accessed in tests in this manner: wrapper.vm.state.hello = 'mad-world' ...

Angular 6 universal website using a .net template is experiencing difficulties with publishing because of the uglifyjs-webpack-plugin

I'm encountering an issue while trying to deploy my Angular 6 universal application with a .net template. The error message I am receiving is as follows: C:\Program Files\dotnet\sdk\2.1.300\Sdks\Microsoft.NET.Sdk&bsol ...

Issue when calling .create() method on Mongoose schema: "this expression is not callable" error in TypeScript

Encountering an error with the .create method on a mongoose model in Next JS while making a call in an API route. The get request is functioning properly... The structure: pages>API>task.tsx import dbConnect from "../../util/dbconnect"; im ...

Managing Angular subscriptions to prevent memory leaks when making API requests

When I first delved into Angular, a colleague suggested using take(1) for API calls with observables in RxJs, claiming it automatically unsubscribes after one call. Believing this, I continued to use it until noticing significant rendering delays when nav ...

Is it feasible to stop closure from capturing external variables in TypeScript?

Imagine I have the following piece of Typescript code: const a = 456 const b = () => a Is there a way to make the Typescript compiler detect and flag an error or warning during compilation indicating that function b is accessing an external variable a ...

Creating a personalized React date selection tool using TypeScript

After following the instructions in the documentation for creating a custom datepicker, I finally managed to build one. However, I encountered an error stating "Function components cannot be given refs. Attempts to access this ref will fail. Did you mean ...

Is the user logged in and ready to be redirected to the dashboard through React router?

I am in the process of creating a redirection feature. The goal is to redirect users who are already logged in from the homepage (visible to all) to the dashboard (only visible to logged-in users). Here is my current implementation: export const PublicRo ...

Positioning 3D objects in Three.js

I am working on a 3D Scene using Three.js with an Earth shape that currently looks like this: https://i.sstatic.net/zXWki.png My goal is to modify it to resemble something like this: https://i.sstatic.net/w4ypV.jpg The coloring, stars, and texture are ...

Clear form values in react-hook-form upon form closure

Featuring the given component: import { yupResolver } from '@hookform/resolvers/yup'; import { useForm } from 'react-hook-form'; import * as yup from 'yup'; import { useToggle } from '../shared/hooks'; import { Su ...

TypeScript Tutorial: How to retrieve the data type of a deeply nested object

I have a question about extracting the type of a nested object with similar structures. The object in question contains multiple sub-objects that all follow the same pattern. const VALUES = { currentStreak: { display: "Current streak", ...

Oops! A mistake was made by passing an incorrect argument to a color function. Make sure to provide a string representation of a color as the argument next time

Encountering an issue with a button react component utilizing the opacify function from the Polished Library The styling is done using styled-components along with a theme passed through ThemeProvider. Upon testing the code, an error is thrown. Also, the ...

In Angular 11, there is a potential for an object to be null

When running the code below, I encountered an error stating Object is possibly null in line +localStorage.getItem('PID'): newPropID() { if (localStorage.getItem('PID')) { localStorage.setItem('PID', String(+localStorage. ...

Discovering the most accurate numeric column definition

In order to consolidate data from multiple columns into one unified column, I am seeking to identify the most precise column type among a range of possibilities. These types include numerical variations such as float, long, double, and various precisions a ...