Error message: jQuery has not been defined for bootstrap4-toggle

Within my app.js, I have included the following:

import $ from 'jquery'
import 'bootstrap'
import 'bootstrap4-toggle'

window.$ = $
window.jQuery = $

However, an error has arisen:

Uncaught ReferenceError: jQuery is not defined
    at eval (bootstrap4-toggle.js:182)
    at Object../node_modules/bootstrap4-toggle/js/bootstrap4-toggle.js (app.js:1407)

I suspect that the import occurs prior to the assignment of window.jQuery = $. Even after attempting to rearrange the order by placing import 'bootstrap4-toggle' below, the issue persists.

What aspect did I overlook?

Answer №1

bootstrap4-toggle relies on the global presence of jQuery and does not explicitly import it. This can cause issues with build systems that do not produce global variables or allow writing to window by default. Depending on your build system, you may need to make adjustments.

Vite Build System

If you are using Vite, you can install @rollup/plugin-inject:

$ npm i @rollup/plugin-inject -D

Then add the following to your vite.config.js:

import { defineConfig } from 'vite';
import inject from '@rollup/plugin-inject';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    inject({
        // remember to add `jquery` in `dependencies` for `package.json`
        jQuery: "jquery",
        $: "jquery"
    })
  ]
})

With this setup, you won't need to manually import 'jquery' in your scripts anymore. Any reference to jQuery or $ will automatically use the globally injected value.

Note: If a script does not use the injected value, it will not be included. Make sure to utilize it at least once during testing.

Webpack

If you are using webpack, you can use ProvidePlugin in your webpack config like this:

plugins: [
  new webpack.ProvidePlugin({
    $: 'jquery',
    jquery: 'jquery',
    'window.jQuery': 'jquery',
    jQuery: 'jquery'
  })
]

JS Modules

In JavaScript Modules, there is no default global window pollution. However, if you want to add jQuery to the window object for standalone scripts, you can do so explicitly like this:

Object.assign(window, { $: jQuery, jQuery })

Further Reading

  • How to use a jQuery plugin inside Vue
  • How to use jQuery with Laravel and Vite
  • How to use Bootstrap 4 and jQuery with Vite v2

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

Creating a gradient border that rotates 360 degrees on mouse hover

.brand-img::after { content: ''; position: relative; background-image: url('https://i.sstatic.net/Y2vyB.png'); background-repeat: no-repeat; float: left; margin-left: 15px; transition: all 1.8s ease; width: 135px; height: 135px ...

Create spinning wheel - canvas

Hey there! I'm trying to create a cool spinning wheel using a canvas and JS. My wheel is supposed to have 10 segments, each saved as a .png file. https://i.sstatic.net/glN1p.jpg In order to achieve a "full circle", I want to draw these 10 segments i ...

Deleting an object with javascript in django: A step-by-step guide

Is there a way to use JavaScript to create a confirmation window before deleting an item? <div class="card-footer"> <a href="{% url 'course_delete' student.slug %}"><button>Delete</button>&l ...

Don't initiate the next fetch until the previous one has completed

I am currently working on sending a list of data to Google Cloud. The code I have been using is as follows: const teams = ['LFC', 'MUFC', 'CFC']; teams.forEach(team => { fetch({ url: URL, method: 'PUT ...

Experiencing issues with Errors when Targeting ES5 in Angular2 TypeScript?

In my development environment, the npm version is 3.10.10, and I want to create a new Angular2 project from scratch. When I try running npm install angular2 --save I encounter this error message: Error Image After referring to this answer which recomm ...

Dealing with numerous validations upon submission in Vue.js

Greetings! I have a requirement to check and validate multiple inputs before allowing the user to submit: <button type="submit" v-on:click="validateErrors()" @click.prevent="submit">Finalize</button> I have crea ...

When the key property is utilized, the state in react useState is automatically updated; however, for updating without it, the useEffect or a

I am working on a component that looks like this: import React, { useState } from "react"; import { FormControl, TextField } from "@material-ui/core"; interface IProps { text?: string; id: number; onValueChange: (text: stri ...

Concealing the BrowserStack key within Karma

Currently in the process of developing a JavaScript application, I am running tests using Karma on BrowserStack with the assistance of the karma-browserstack-runner. According to the guidelines, the accessKey and username should be included in the karma co ...

Tips for adjusting the height of both an iframe and a div to fit perfectly at 100% combined

Struggling to make an iframe and div both have 100% full height on the page? I need a footer menu with 280px height, leaving the rest of the page for the iframe. After extensive research, it seems like jQuery might be necessary as CSS Flex didn't wor ...

Is there a way for me to gain access to alter the price function within Magento?

Now, I am faced with the task of customizing the discounted price for my Shopping cart. After some independent research, I discovered that by modifying the view.phtml and item.phtml files, I can properly display the desired price. However, I still feel uns ...

Tips for setting up nested folders using Node.js on a Windows machine:

Is there a way to use Nodejs in Windows 10/11 to create a parent folder and then add a new folder inside of that parent folder, like this: parent/child within the Documents folder? ...

Adding JSON content to a form for editing functionality within an Angular 8 CRUD application

I am currently working on building a Single Page Application using Angular 8 for the frontend and Laravel for the backend. I have been able to successfully pass data to the backend via JWT, and everything is functioning as expected. The application follows ...

Struggling to locate the 'babel-runtime/regenerator' module? Consider importing it locally versus from NPM for a seamless integration

I've been encountering issues with my babel configuration while working on an NPM module that utilizes ES6 features like async/await, static class methods, and import/export. Initially, I faced the common error ReferenceError: regeneratorRuntime is n ...

"Utilizing Material-UI in React to create a textfield input with number validation

I am currently working on an input field that should only accept values within a specified range of min and max. However, I have encountered an issue where manually entering a number bypasses this control mechanism. Is there a way to prevent this from happ ...

Exploring React-Redux: The Origin of Children Components

Currently, I'm following a tutorial on react-redux which can be found at the following URL: http://redux.js.org/docs/basics/ExampleTodoList.html As I analyze the code in link.js, I'm curious about the source of the {children} element. import R ...

Using router-links with events: A simple guide

My current issue involves passing information to another page. During testing without using routes, I was successful in passing information from one component to another. However, after implementing routes, clicking the event navigates to the other compo ...

I am experiencing issues with my JavaScript not functioning properly in conjunction with my HTML and CSS. I am uncertain about the root cause of the problem (The console is displaying an error message:

I am facing challenges in creating a content slider and encountering issues with its functionality. Specifically, when testing locally, I noticed that the current-slide fades out and back in upon clicking the arrows left or right, but the slide content is ...

Navigating Through Different Environments in Your React Application

Currently, I am tackling a small project where I am utilizing React for the frontend and Java for the backend. The project involves two distinct environments. My main struggle revolves around effectively managing multiple environments. To set the API URL, ...

When using a custom AJAX function, make sure that bindings are functioning properly when setting properties within a callback in Ember

I've encountered some unexpected behavior while trying to set an Ember property inside a custom AJAX function callback. The AJAX function is triggered in the route, as seen in the code snippet below. The success callback updates the 'session.aja ...

Add HTML content to a specific div according to the option selected in a drop-down menu

I am currently working on a project where I need a button to insert HTML content into a div based on the value selected in a select box. However, the functionality is not working as intended. Upon clicking the button, nothing happens. I am unsure of what t ...