The module named "jquery" has not been loaded in this context: _. Please use require() to load it

As I work on migrating my Javascript files to Typescript, I encountered an issue when trying to use the transpiled javascript file in an HTML page. The error message I received is as follows:

https://requirejs.org/docs/errors.html#notloaded
at makeError (require.min.js:1)
at Object.s [as require] (require.min.js:1)
at requirejs (require.min.js:1)
at helloworld.js:4

Below is my Typescript file:

import * as $ from "jquery";

export class Loading {
  public showLoadingModal(msg?: string) {
    if (msg === undefined) {
      msg = "Loading ...";
    }
    $("#dialog1 label").html(msg);
  }

  public hideLoadingModal() {
   
  }

  public keepOpenLoadingModal() {
    $("#dialog1").on("hide.bs.modal", function () {
      return false;
    });
    this.showLoadingModal();
  }
}

And here is the transpiled Javascript file:

"use strict";
exports.__esModule = true;
exports.Loading = void 0;
var $ = require("jquery");
var Loading = /** @class */ (function () {
    function Loading() {
    }
    Loading.prototype.showLoadingModal = function (msg) {
        if (msg === undefined) {
            msg = "Loading ...";
        }
        $("#"dialog1 label").html(msg);
       
    };
    Loading.prototype.hideLoadingModal = function () {
       
    };
    Loading.prototype.keepOpenLoadingModal = function () {
        $("#dialog1").on("hide.bs.modal", function () {
            return false;
        });
        this.showLoadingModal();
    };
    return Loading;
}());
exports.Loading = Loading;

I have loaded jQuery from a CDN like so:

<html lang="en">
<head>
<meta charset="utf-8" />
...
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
...  

I also tried loading JQuery using the code below but encountered issues:

      
<script>
  var exports = {};
</script>
...
Can someone please provide assistance in resolving this error? Any help would be greatly appreciated as I am stuck at this initial stage of my migration journey.

Answer №1

You successfully converted the TypeScript code to CommonJS format.

Remember, web browsers do not support the CommonJS module system; they only support ECMAScript modules.

The library you're using, requirejs, is compatible with the AMD module system.


To address this issue during transpilation, consider targeting browsers specifically. This can be achieved through tools like Webpack, which offers a loader for TypeScript modules.


On a side note: If you are bundling jQuery through import, avoid loading it from a CDN simultaneously.

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

Using Angular: Binding Angular variables to HTML for display

I have a component with a ts file that contains HTML content as a variable. Let's say para1= <a href="www.google.com">sitename</a> more content I want to bind this paragraph in HTML as if it were actual HTML tags. sitename What is the ...

Issue with scroll being caused by the formatting of the jQuery Knob plugin

I am currently utilizing the jQuery Knob plugin and I am looking to have the displayed value shown in pound sterling format. My goal is for it to appear as £123456. However, when I attempt to add the £ sign using the 'format' hook, it causes is ...

What could be causing the error when attempting to send an HttpResponse from a Django View function?

Trying to utilize Ajax, I'm attempting to call a Django View function from JavaScript code. The View function is expected to return an HttpResponse, which should then be printed out on the console. However, upon inspection of the console, it simply s ...

Exploring the new possibilities of Angular 5: Enhanced REST API service with paginated data and object mapping capabilities

After implementing pagination in my REST API backend, I now need to update my Angular services to accommodate the changes. Instead of simply returning an array of objects, the API will now return JSON responses structured like this: { "count": 0, ...

CRUD operations are essential in web development, but I am encountering difficulty when trying to insert data using Express

I am currently attempting to add a new category into the database by following the guidelines provided in a course I'm taking. However, I am encountering difficulties as the create method does not seem to work as expected. When I try it out in Postman ...

The npm script for running Protractor is encountering an error

Currently, I am facing an issue while trying to execute the conf.js file using an npm script. The conf.js file is generated within the JSFilesRepo/config folder after running the tsc command as I am utilizing TypeScript in conjunction with protractor-jasmi ...

I'm having trouble getting my CSS opacity to smoothly transition back to its original state of .5 using setTimeout(). What could be

I recently started learning JS, Jquery, and CSS. My goal is to create a Simon Says style game. However, when I attempt to animate the computer to automatically light up the correct square, I faced some challenges. To address this issue, I decided to star ...

The issue with the Hidden Content feature in the Slick Carousel is that it does not function correctly on the

There are some related topics worth exploring, such as: Slick carousel center class not working when going from last item to first item Despite trying various solutions, the issue still persists in my code. My goal is to have each item displayed in the ce ...

Attempting to integrate the Angular2 module text-mask-addon into the project

Currently, I am in the process of integrating text-mask-addons into my Angular application. You can find more information at https://github.com/text-mask/text-mask/tree/master/addons Despite attempting to follow the npm links suggestion, I am encountering ...

Is it possible to extract a user's password from the WordPress database for use in a React application

Is it feasible to create a React application integrated with Postgres within Wordpress that operates on MySql? I am interested in leveraging Wordpress's built-in features for theming, posts, and user management accounts. However, I am unsure if I can ...

Feeling puzzled about the next() function in Node.js?

https://github.com/hwz/chirp/blob/master/module-5/completed/routes/api.js function isAuthenticated (req, res, next) { // If the user is authenticated in the session, call the next() to proceed to the next request handler // Passport adds this met ...

A unique directive that showcases both default and custom errors sequentially

In my project, I am facing a challenge where I need to compare the input text with a series of inbuilt errors such as required, minlength, maxlength, and pattern. Additionally, I also need to validate the input against a custom condition using a Custom Val ...

Create a new visual masterpiece using Canvas by repurposing an

I am currently working on the following code snippet; export default async function draw(elRef : RefObject<HTMLCanvasElement>, tileData : TileProps) { const canvas = elRef.current!; const ctx = canvas.getContext('2d')!; ctx.clearRect( ...

Ways to achieve combined outcomes using ng-repeat

Check out this plunker. <div ng-repeat="subCategory in subCategorys | filter:{tags:tag}:true | orderBy:'id'"> {{subCategory.id}} {{subCategory.name}} {{subCategory.tags}} <br/><br/> The detailed information of ...

After the table finishes loading, my goal is to display an export to Excel button

I am currently working on generating an HTML table using JSON data received from the backend Java application. My objective is to display an "Export to Excel" button after populating the table. The process involves users entering dates and selecting option ...

In Typescript, the module source is imported rather than the compilation output

I created a custom module for personal use and decided to host it on a private GitHub repository. Within the module, I have included a postinstall script that runs: tsc -d -p .. Currently, the generated .js and .d.ts files are located alongside the source ...

Troubleshooting: Unable to modify value with function in AngularJS

Why can't I change a value using a function in AngularJS? html: <div ng-controler='TestCtrl' id='TestCtrl'> <h1>Test: {{test.name}}</h1> <div ng-hide='showTest'> <div class=&a ...

Stop the form submission until validation is complete

I'm currently working on a form and encountering some validation issues. HTML: <form id="regForm" class="form-group" method="POST" action="signup.php"> <div class="col-md-12"> <h2>Job Pocket</h2> </div> <di ...

Maintaining state value during client-side navigation in NextJs with Next-Redux-Wrapper

Currently, I am working on resolving the hydration issue that occurs when using wrapper.getServerSideProps. The problem arises when I reroute with the existing setup and the store gets cleared out before adding new data. This leads to a blank page as essen ...

Exploring the usage of array map parameters in rxjs 6 when combined with withLatestFrom

Prior to Rxjs 6, we were able to achieve the following: interface TypeA { payload: any; } source$.pipe( withLatestFrom(source2$, (source1: TypeA, source2: TypeB) => ({ payload: source1.payload, source2 }) ), ) In the resultSelector method ...