How to Fix the Undefined Issue with the Bootstrap-toggle JQuery Plugin in a Webpack and Types

Having trouble integrating the JQuery plugin bootstrap-toggle into my Webpacked Typescript project. Every time I try to call it, I encounter an error stating is not a function and find that the handle is undefined.

I realized webpack was not including the module, so I added an import for it at the top.

import * as $ from 'jquery';
import 'bootstrap-toggle';
$("#test-toggle").bootstrapToggle();

HTML:

<label>
    <input id="test-toggle" name="testtoggle" data-toggle="toggle" type="checkbox">
    Test Toggle
</label>

Webpack config:

const path = require('path');

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

Webpack output:

[webpack-cli] Compilation finished
asset bundle.js 199 KiB [emitted] [minimized] (name: main) 1 related asset
modules by path ../node_modules/ 532 KiB
  modules by path ../node_modules/bootstrap/ 73.6 KiB 13 modules
  ../node_modules/jquery/dist/jquery.js 281 KiB [built] [code generated]
  ../node_modules/bootstrap-toggle/js/bootstrap-toggle.js 5.41 KiB [built] [code generated]
modules by path ./ 632 b
  modules by path ./*.ts 632 b
    ./app.ts 632 bytes [built] [code generated]
webpack 5.4.0 compiled successfully in 5743 ms

The versions I'm using:

"@types/bootstrap": "^5.0.0",
"@types/bootstrap-toggle": "^2.2.1",
"@types/jquery": "^3.5.4",
"bootstrap": "^3.4.1",
"bootstrap-toggle": "^2.2.2",
"jquery": "^3.5.1",
"ts-loader": "^8.0.11",
"typescript": "^4.0.5",
"webpack": "^5.4.0"

Answer №1

After some investigation, I discovered that my webpage was loading both an external JQuery library and my bundle.js file, which I had mistakenly left in during testing.

As a result, I encountered an error stating that JQuery was undefined. To resolve this issue, I modified the library by incorporating a wrapper from another JQuery plugin.

(function(factory){
    if (typeof define === 'function' && define.amd){
        define(['jquery'], factory);
    } else if (typeof module === 'object' && typeof module.exports === 'object') {
        module.exports = factory(require('jquery'));
    } else {
        factory(jQuery);
    }
} (function(jQuery) {

// ... boostrap-toggle code

return jQuery.bootstrapToggle;}));

With this adjustment, everything is now functioning correctly.

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

Typescript throws an error when attempting to return an array of strings or undefined from a function

I created a shallow differences function that compares two arrays of strings and returns either undefined (if the arrays are different lengths) or a string array containing matching characters at corresponding indexes. If the characters don't match, i ...

What could be the reason for the malfunctioning of jquery hover functionality?

My goal is to develop a unique text editor that can send Ajax requests when a word is hovered. The code snippet below shows my progress so far: <div class="word_split" contenteditable="true">Don't break my heart.</div> Included in the pa ...

Issue: "A further loader may be required to manage the output produced by these loaders."

I'm encountering an issue while developing a web page using Vue.js and webpack. The problem arises when I try to add a style in a single file component called Curry.vue, as the build process fails. <template> <div> </di ...

Merge the date and time values to create a unified datetime

I'm working with a date and time control and I need to combine the values. var startDate = jQuery('#startDatepicker').find("input").val(); var startTime = jQuery('#startTimepicker').find("input").val(); Another variable in my cod ...

Adding HTML elements dynamically using jQuery: A how-to guide

My objective is to start with one element upon loading the page, and this element should have an ID of "something_O". When the user clicks on an add link, a new identical HTML element should be added underneath the existing element. The new element should ...

How to resolve the "cannot find module <module>" error when using ES6 modules in Typescript

There is a file located in src/shared/components/A.tsx that contains import B from 'components/B' (found in src/shared/components/B.tsx) Upon compiling, Typescript throws an error saying cannot find module 'components/B' Below is the ...

Creating a Dynamic Bootstrap 4 Dropdown Menu using Jquery Hover

My Bootstrap Dropdown menu has a JQuery animation that is exactly what I want. However, when I move my cursor from the Dropdown's name (.dropdown) to an item in the dropdown, it starts acting erratically. $('.dropdown').hover(function() { ...

JQuery ajax issue: Resolving the 'No Transport' error in CRM 2011

Currently, I am working on CRM 2011 where I have implemented two buttons with JavaScript functionality. One of the buttons is responsible for making a webservice call within the same domain, while the other button triggers an ODATA update request to the sa ...

Exporting types with the `export =` syntax in TypeScript

For a code base that utilizes typescript export = syntax, I am looking to incorporate a new feature. The current code exports a function while also adding properties to it: const f = () => {}; f.someVal = 123; f.someFunc = () => {}; export = f; This ...

Ways to integrate object-or-array with recursion in Typescript

I am striving to achieve the following: type Foo = ({bar: string} & Record<string, Foo>) | Foo[] However, I keep encountering issues such as circular references in type or the constraint that An interface can only extend an object type or inte ...

What is a straightforward method to display one Div while concealing all others?

Is there a simpler method to display one div and hide all others, with the first one shown by default? My current solution using jQuery works, but it feels lengthy. I believe there might be a more efficient way to achieve this. Here is the code snippet: ...

Setting up React Context API with TypeScript: A Step-by-Step Guide

I recently updated my app.js file to app.tsx for improved functionality. However, I encountered an error with the current value. app.tsx import React, { createContext, useState } from "react"; import SelectPage from "./pages/select/select& ...

Invoking Jquery on the server side in an asp.net environment

I am interested in incorporating this plugin into my asp.net application. I am currently serializing the title and text server-side using this class, which I have successfully implemented. However, I am faced with a challenge: I need to load titles and con ...

Is it possible to have HTML text that changes dynamically before loading?

My collection of flow charts requires each block to open a specific question when clicked. The question page has a standard template with only the heading changing. Rather than creating individual HTML files for each question, I am seeking a way to dynamic ...

Receiving a ModuleParseError when attempting to import an SCSS file in Nextjs 13

I am working with Next.js v13 in a monorepo structure. I am facing an issue when attempting to import a scss file within another scss file, resulting in the following error: ModuleParseError: Module parse failed: Unexpected character '@' (1:0) Yo ...

Having trouble interpreting the response using jQuery

Upon running my PHP script, I am receiving the following response. PHP: <?php $con = mysqli_connect("localhost","root","pass","products"); if(mysqli_connect_errno()) { echo "Failed to connect database, please check with your administrator. Error ...

Is there a JavaScript alternative to WinHttpRequest?

I've been exploring the possibility of using an API on my website and I currently have a functioning VB example that works in VBA. I'm wondering if there is a way to replicate this functionality using Javascript. Set http = CreateObject("WinHttp ...

Communication through SocketIO broadcast to all clients isn't functioning as expected

I am currently working on setting up a socketIO server in NodeJS using Typescript. My goal is to have the server send a message to all connected sockets, including itself, every 1000ms. I have successfully set up the base socket and verified that the &apo ...

Determining User Login Status in Laravel using jQuery

While I am familiar with the authentication verification in laravel, I am interested in learning how to verify it using jQuery. Specifically, I want to make changes to my CSS when a user is logged in. By default: body{ background: url('image.jpg ...

Using Angular Form Builder to assign a value depending on the selected option in a dropdown menu

My approach to Angular Form Builder initialization includes a group that looks like this: contactReason: this.formBuilder.group({ description: '', source: this.sourceType() }) For the 'description' field, I hav ...