Tips for stopping TypeScript from halting Webpack compilation due to undefined variables stated in Webpack's ProvidePlugin

Is there a way to prevent WebPack's build process from failing when the TypeScript compiler throws errors about unresolved variables that are already configured in Webpack's ProvidePlugin settings?

webpack.config.js

plugins: [
...
new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            "window.jQuery": "jquery",
            "_": "underscore",
            "underscore": "underscore"
            //'process.env.NODE_ENV': '"development"'
        }),

]

tsconfig.json

{
  "compilerOptions": {


    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "suppressImplicitAnyIndexErrors": true,
    "declaration": false
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

Based on my experience, TypeScript doesn't recognize the variables injected into the module, causing the build to fail.

This is the build output

ERROR in ./src/file1.component.ts
(77,9): error TS2304: Cannot find name '$'.

ERROR in ./src/file2.component.ts
(78,13): error TS2304: Cannot find name '$'.

ERROR in ./src/file3.ts
(155,15): error TS2304: Cannot find name 'jQuery'.

ERROR in ./src/file4.ts
(108,9): error TS2304: Cannot find name '$'.

Answer №1

I found a solution that worked better for me than ahz's answer. I prefer not to install typings globally or declare jQuery as any and losing all typechecking.

To address this, I created a file called global.d.ts with the following content:

import * as _jQuery from 'jquery';

declare global {
  const jQuery: typeof _jQuery;
  const $: typeof _jQuery;
}

With this in place, when running tsc, I no longer receive warnings like Cannot find name '$'..

This helpful tip was found here.

Answer №2

It's important to remember that even with the ProvidePlugin in webpack, you still need to have jQuery and underscore declared as modules (externals or alias).

To ensure proper loading of these modules in TypeScript, I recommend using the following syntax:

import * as $ from 'jquery';
import * as _ from 'underscore';

Make sure to provide definition (.d.ts) files for these libraries, which can be done easily with a tool like typings.

typings install jquery --global
typings install underscore --global

If you're using ts-loader, it should handle this process automatically.

If you prefer not to use import statements, you can declare the libraries with typings definitions, or create simplified declarations like so:

declare var jQuery: any;
declare var $: any;

Answer №3

In addition to the top answer, I would like to mention that there are some exceptions and ways to solve them. In my experience tackling this issue, I utilized Ant-Design and Redux.

One way to address this is by using the following code snippet:

import _Fake from 'fake-lib'

declare global {
  const Fake: typeof _Fake
}

This method works well for libraries that have been exported as a namespace (such as React). For such cases, you can confidently do this:

const x: Fake.Property // Success: Fake serves as a namespace
Fact.Function          // Success: Fake represents a concrete type containing Function

However, there were instances where certain libraries did not export as a namespace (like Redux) which led to issues like:

const x: Fake.Property // Failure: Fake is not recognized as a namespace
Fact.Function          // Success: Fake acts as a concrete type that includes Function

To tackle this problem, one workaround is to globally augment the library to be treated as if it were a namespace export:

You can achieve this by making modifications to your tsconfig.json file:

"compilerOptions": {
    ...
},
"include": [
    "./src/**/*",
    "./types/**/*"
]

Additionally, create a types/fake.d.ts file with the following content:

import * as Fake from 'fake-library'

export as namespace Fake
export = Fake

By implementing these changes, the global const declaration should function correctly as intended.

Answer №4

Avoid mixing babel-loader and ts-loader(remove the latter) after migrating to babel 7! I trust this tip will prevent others from encountering debugging issues later on! Source

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

Next.Js Exported static HTML file is unable to locate CSS and JS files due to a wrongly configured path

When I export static html files on Next.Js, the href and src directory in HTML are not linking to the "_next" folder. I have to manually adjust it by adding "../../" in the index.html for it to work correctly. The same issue arises with JS files as well. ...

The module for the class could not be identified during the ng build process when using the --

Encountering an error when running: ng build --prod However, ng build works without any issues. Despite searching for solutions on Stack Overflow, none of them resolved the problem. Error: ng build --prod Cannot determine the module for class X! ...

Retrieving and merging data from an API using Angular 6

Is it possible to retrieve data from an API and gather each user's posts along with their comments in a single JSON object? To fetch posts, you can utilize the following API: https://jsonplaceholder.typicode.com/posts As for retrieving comments, you ...

Error in TypeScript React: 'Display' property is not compatible with index signature

My design page in React with TypeScript template is using Material UI, with custom styles implemented using the sx prop of Material UI. To customize the styling, I have created a separate object for the properties related to the sx props: const myStyles = ...

In Visual Studio, the .js.map files and .js files seem to be mysteriously hidden, leaving only the TypeScript .ts files visible

In the past, I utilized Visual Studio Code for Angular 2 development and had the ability to hide .js and .js.map files from the IDE. Now, I am working on a project using VS 2017 Professional with Typescript, Jasmine, Karma, and Angular 4. Task Runner, etc. ...

Facing issues with utilizing branded keys in conjunction with object spreading?

I've encountered a peculiar situation while using branded strings as keys in an object with TypeScript. The compiler fails to flag what I believe are clear type errors in certain scenarios. Here is a simplified version of the issue: type SpecialKey = ...

Validation messages in an Angular application using Typescript are failing to display or disappear sporadically when applied to an HTML form that has

I am currently working on a simple app that retrieves website content from a CMS [Umbraco]. After making an Ajax call, the form comes back to me as plain HTML. I then append the form to the page and use the Angular $compile service to compile the result. T ...

Is there a way to eliminate the numeric labels on the bars of a primeng bar chart?

I am trying to get rid of the numbers displayed on the bar graphs. I need some guidance on what changes to make in the Options array to achieve this. You can view my graph here: https://ibb.co/G7nR3mz Below is the Options array I am working with: this ...

Nestjs struggles with resolving dependencies

Having trouble finding the issue in my code. (I'm still new to nestjs and trying to learn by working on some apps). The console log is showing the following error: Nest can't resolve dependencies of the UrlsAfipService (?). Please ensure tha ...

A new issue arises after merging in Google Datastore, as an unexpected property is

Currently, I am working on developing an API in Typescript to interact with a Google Cloud Datastore instance for storing and retrieving entities. So far, I have successfully implemented the GET, POST, and DELETE methods. However, I encountered an issue w ...

Express Server Providers for Angular 17's Server-Side Rendering

I attempted to share my request and response object with the Angular application by defining Providers in the "server.ts" file. However, when injecting them into app.component, they always appear undefined regardless of whether I am in the server or clie ...

Incorporating an Ionic application into a Rails 4 application

Seeking guidance on integrating an Ionic 2/3 app with a complex Rails 4 app. What would be the optimal approach for this task? How can I seamlessly add an API to an already intricate application? ...

Why aren't the child route components in Angular 6 loading properly?

I have encountered a small problem. I developed an app using Angular 6 with children routes implemented like this: { path:'pages', component:DatePagesComponent, children : [ {path:'404', component:Error404C ...

Angular routing is showing an undefined ID from the snapshot

When a user attempts to update a student, I pass in the student ID. The update successfully redirects to the updateStudent page and displays the student ID in the browser link. However, within my app component, it shows as undefined. Student View componen ...

Include a string in every tuple

I am trying to define a new type: type myNewType = 'value-1' | 'value-2' | 'value-3' Is there a way to create another type like this? type myNewType2 = '1' | '2' | '3' However, I want the outpu ...

Encountering an undefined property error when trying to access 'userService' while implementing an async validator in Angular 12

For the past few days, I've been struggling to implement async validation with no success from various tutorials and solutions! Service code- getUserIdToCheckDuplicate(userId:any):Observable<any>{ const url = ``; //url goes here return ...

Discover the method for converting a local file into a string

Looking to retrieve and read an SVG file in Angular 6 from the assets folder as a string. I've attempted the following: this._htmlClient.get('../../assets/images/chart1.svg').subscribe(data => { console.log('svg-file: ', ...

Trouble with querying NG elements using "queryAll(By.css)" in Angular and Jasmin unit testing

I've encountered an unusual problem that needs to be resolved for me to successfully complete a unit test for a project I'm currently engaged in. Here is what my unit test currently looks like: it('should display the navbar list', ...

Cypress: Uncovering the method invoked by a button click

I'm currently utilizing Vue3 with Vite and Cypress. My Vue3 component utilizes the script setup SFC syntax. Below is the code snippet for my component: <template> <div> <button data-cy="testBtn" @click="btnClick()&q ...

Leverage the exported data from Highcharts Editor to create a fresh React chart

I am currently working on implementing the following workflow Create a chart using the Highcharts Editor tool Export the JSON object from the Editor that represents the chart Utilize the exported JSON to render a new chart After creating a chart through ...