Learn the steps to import and utilize individual BootStrap 5 JavaScript Plugins

I am currently diving into the world of Bootstrap (v5.1.0) and gulp, but I'm a bit confused about how to import specific Bootstrap JavaScript plugins. I attempted to bring in only the modal plugin from Bootstrap, but encountered either a syntax error or no response when trying to launch the modal.

The following is my index.html showcasing the modal example from Bootstrap 5 documentation

<head>
  ...
  <script src="main.js" async></script>
  <link rel="stylesheet" href="main.css">
</head>
<body>
  <!-- Button trigger modal -->
  <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
    Launch static backdrop modal
  </button>

  <!-- Modal -->
  <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="staticBackdropLabel">Modal title</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          ...
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Understood</button>
        </div>
      </div>
    </div>
  </div>
</body>

My intention was to import the necessary JS plugins (found at js/src/ in the Bootstrap package) at the beginning of the main.js file:

(async function main() {
  import BaseComponent from 'bootstrap/base-component.js'
  import Modal from 'bootstrap/modal.js'
  const {myConfig} = await import("./myconfig.js");
  ...
})();

Alternatively, I also attempted importing them like this:

import { BaseComponent } from 'bootstrap/base-component'
import { Modal } from 'bootstrap/modal'

(async function main() {
  const {myConfig} = await import("./myconfig.js");
  ...
})();

If someone could guide me on how to selectively import Bootstrap's JS plugins or provide best practices for working with Bootstrap's JS plugins, I would greatly appreciate it. Currently, I compile my website source files using gulp - just in case that affects the situation.

Answer №1

It's important to consider how your main.js and HTML code will be processed before being sent to the browser. Import statements like the ones you've used need to be resolved during compilation using tools like Babel, gulp, or webpack. Without this step, the browser may encounter errors when trying to interpret these statements. During compilation, the import statements are replaced with the actual imported code, so there shouldn't be any issues with import syntax reaching the browser. It's possible to have imports in JS code that runs in the browser, but the syntax and performance implications need to be carefully considered.

If you're encountering a Syntax error related to Imports early in the build process, it could indicate problems with Babel.js or the version being used. Make sure your task runner setup for JS syntax validation is up to date to avoid such issues.

I personally use Webpack 4 with Babel and have successfully tested similar scenarios. Your code seems correct, including the importing of base-component and modal in main.js.

One more thing I noticed (not directly related to your reported issue) is your use of

<script .. async>..

This attribute downloads the script in parallel and can run before the page is completely parsed or its DOM tree is ready. If you plan on performing DOM operations, consider using defer instead of async. Alternatively, placing the script at the bottom of the HTML body can also help ensure proper execution timing.

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

Parsing a Jackson object in JavaScript that includes JsonIdentityInfo

Hey there (excuse my English) I've been working on an AngularJS front-end website that consumes a web service which produces JSON with Spring MVC. The Spring MVC uses the JsonIdentityInfo option for serialization, so each object is only written once ...

Indicator count for multiple slick carousels

Is there a way to create individual slide counters for multiple sliders that do not work together? In my current example, the slide counters are functioning together: https://codepen.io/anon/pen/oqqYjB?editors=1010 <div class="container"> <div ...

Encountering a null value in a function parameter assigned within an AJAX success callback in JavaScript

function fetchData(url) { var response = null; $.ajax({ type: "GET", url: url, crossDomain: true, async: false, contentType: "application/json; charset=utf-8", da ...

Angular 2 click event with changing function name

Even though this question seems simplistic, I'm having trouble figuring it out. As someone new to Angular 2, I've tried various combinations of {}, [], and () brackets to make the following work: <button (click)="this.action">Click me</ ...

JavaScript can be used to activate the onclick event

Is there a way to disable and then re-enable all buttons that share the same class name? I attempted the following code without success: let buttons = document.getElementsByClassName("btn-st"); for (let i = 0; i < buttons.length; i++) { b ...

Changes in a deep copy of an object in a child component are directly reflected in the parent object in VueJS

Let's begin by discussing the layout. I have a page dedicated to showcasing information about a specific company, with a component Classification.vue. This component displays categories of labels and the actual labels assigned to the current company. ...

Customizing the appearance of columns in an antd table

Below is the table column configuration I am working with, where notes are rendered using a custom function: fieldDefs: (results, isJsonData) => [ { title: 'Notes', name: 'notesHTML', table: { render: SectionNotes, sear ...

How can one utilize JSON.parse directly within an HTML file in a Typescript/Angular environment, or alternatively, how to access JSON fields

Unable to find the answer I was looking for, I have decided to pose this question. In order to prevent duplicates in a map, I had to stringify the map key. However, I now need to extract and style the key's fields in an HTML file. Is there a solution ...

Use jQuery's .each method to reiterate through only the initial 5 elements

Is there a way to loop through just the initial 5 elements using jQuery's each method? $(".kltat").each(function() { // Restrict this to only the first five elements of the .kltat class } ...

Is there a way to programmatically update a webpage using Javascript?

I have been attempting to set up the code in a way that the page automatically changes using setTimeout. However, I am unable to make it work. setTimeout()(page3, 500); function page3() { changepage3('automatic') } Even though my code is str ...

experiment with jest and react-testing-library for testing functions

I'm having trouble accessing a method inside a functional component in React using Jest and react-testing-library. I attempted to use enzyme, but it seems like everything is shifting towards RTL instead. import React from "react"; const simpleCompo ...

Differences seen in display when using Internet Explorer's prependTo feature

Here is some code that I am working with:- <ul id="list1"> <li class="a">item 1</li> <li class="a">item 2</li> <li class="b">item 3</li> <li class="b">item 4</li> </ul> Additiona ...

Discovering the value of a chosen star and saving it in a database with the help of jQuery or JavaScript

When a user clicks on the 3rd star in the Jrate Plugin, I need to retrieve the value of 3. This can be achieved using the jRate onSet option. Below is my HTML: <div id="jRate"></div> And this is my JavaScript code: $("#jRate").jRate({ ...

Is it possible to cache an html page and display it on the current page when reloading?

I have been attempting to design a webpage with links in a table that trigger modals when clicked. These links are added dynamically using Jquery. $("table").append('<tr><td><a href="#exampleModal" data-bs-t ...

A white background emerges when I select md-dropdown

Lately, I've been experiencing an issue on my website where a white background pops up whenever I click on a dropdown (md-select) in my form. Initially, it only happened with forms inside a modal, but now it's affecting dropdowns across the entir ...

Align numbers vertically inside scrollbar center

I have created a program where you can input a number, and it will count from 0 to the specified number. Currently, the numbers are aligned horizontally up to 12 before starting on a new line. However, I would like the numbers to be arranged vertically fr ...

Creating a script that automatically launches the terminal and executes specific commands

Can anyone help me with creating a file that, when clicked on, opens a command prompt and executes the following commands? cd desktop\discordBOT node . Many thanks in advance! ...

What is the best way to stack col-xs-6 elements instead of having them side by side?

My form fields are currently set up using 3 col-xs-6 classes, but I'm not seeing the desired layout. I am aiming for: | col-xs-6 | | col-xs-6 | | col-xs-6 | However, what I am getting is: | col-xs-6 | col-xs-6 | | col-xs-6 | I understand that th ...

Obtain the final value within a URL's path segment

If we have an href similar to: http://localhost:8888/#!/path/somevalue/needthis Is there a way to extract the last value in the path string (i.e., "needthis")? I experimented with window.location.pathname, but it only returns "/". Another attempt was m ...

Experiencing issues with implementing shopping cart logic using KnockoutJS. Need help

The Objective Create a dynamic list of products. The Scenario Overview In my online shopping application, I want to showcase the products I add to my shopping list in a sidebar when I click the 'add button' for each product. Brief Problem Sum ...