Utilizing Grunt with Bootstrap 5 for streamlining and optimizing JavaScript code bundling

After successfully bundling the Bootstrap 5 SCSS files using Grunt, I now want to do the same with the JavaScript files. I am using grunt-contrib-uglify for this task:

uglify: {
    site: {
        options: {
            sourcemap: false
        },
        files: {
            'example/static/example/assets/js/example.min.js': [

                // List of JS files to include
                'node_modules/@popperjs/core/dist/umd/popper.js',
                'node_modules/bootstrap/js/dist/dom/data.js',
                'node_modules/bootstrap/js/dist/dom/event-handler.js',
                // Add more files here

                'example/src/js/**/*.js'
            ]
        }
    },
},

After including the minified JS file in my HTML, I encountered an error in the console:

ReferenceError: bootstrap is not defined

I followed the npm bootstrap 5 starter on Github for reference, including all necessary files, such as the Popper dependency and core JS files. However, I seem to be missing something from the bundle. Here is a link to the starter files on Github: Github Bootstrap 5 npm starter

Bootstrap version: 5.1

Popper version: 2.9.2

Edit: The issue was resolved when using the distributed bundle.

Answer №1

element, you have the ability to utilize the grunt uglify task in order to achieve the following:
<script>
    var myOffcanvas = document.getElementById('offcanvasExample')
    var bsOffcanvas = Offcanvas(myOffcanvas)
</script>
This script specifically removes the reference to new bootstrap. as it seems that when importing individual component files, Bootstrap is not brought in as a module. Consequently, it is not accessible in the same manner as when included in a bundle. Furthermore, the separate components can still be imported and utilized as functions, much like the Offcanvas example provided. In an update, bootstrap 5 integrates rollup for its javascript bundling process, prompting a look into the 'grunt-rollup' task. A configuration that aligns more closely with the Bootstrap documentation was eventually achieved through the use of the grunt-rollup task with the given setup:
// gruntfile imports
const babel = require("@rollup/plugin-babel").default;
const path = require('path')
const {nodeResolve} = require("@rollup/plugin-node-resolve");

// rollup task
rollup: {
    options: {
        plugins: [
            babel({
                exclude: './node_modules/**',
                babelHelpers: 'bundled',
            }),
            nodeResolve()
        ],
        globals: {
            '@popperjs/core': 'Popper'
        },
        external: ['@popperjs/core'],
        format: 'umd',
        name: 'bootstrap',
    },
    files: {
        src: path.resolve(__dirname, `path/to/bootstrap5/imports/file`),
        dest: path.resolve(__dirname, `path/to/export/file`),
    },
},
The bootstrap imports file structure includes components like Alert, Button, Carousel, Collapse, Dropdown, Modal, Offcanvas, Popover, ScrollSpy, Tab, Toast, and Tooltip. These components can be selectively included in the javascript file to cater to the specific needs of the project.

Answer №2

While I may not be an expert, I urge caution when it comes to combining libraries like Boostrap into a single main file along with other JS files outside the framework. This can lead to performance issues, potential crashes between libraries, conflicts in definitions, and the risk of penalties from search engines like Google due to lack of proper updates and build processes.

Furthermore, Boostrap usually offers already compressed/minified/uglified .min.css and .min.js files that are optimized for use without customization. It's best to avoid using uncompressed files unless you plan to make significant modifications to the design patterns.

For any additional custom libraries or vanilla JS code you create, tools like grunt-contrib-concat can be beneficial. Additionally, assessing performance with tools like PageSpeed Insights can help identify areas for improvement and optimization.

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

Problem encountered with imaskJS in handling the formatting of data with forward slashes

After conducting tests on the frontend of the imask website at , it has been verified that utilizing a forward slash for date formatting results in the exclusion of the final digit of the date. Various attempts were made, including: IMask( field, ...

Creating tar-ed npm modules: A step-by-step guide

I have incorporated the https://github.com/allegro/grunt-maven-plugin into my workflow for building my Java + Angular JS application. I want to avoid downloading node modules every time I run a build. According to the note provided on https://github.com/a ...

The header() function triggers automatic page redirection instead of waiting for the form to be submitted

When I created a form that automatically sends an email upon submission, my goal was to direct the user to a thank you page after the email is sent. In my search for a solution, I stumbled upon the header() function in php and attempted to use it with the ...

I am experiencing an issue where my JSON array is only returning the last element. Any suggestions on how to

I am facing an issue with my JSON array and Ajax code. Here is the snippet of my code where I upload an Excel file, convert it to JSON, then save it as a string in my database: function exportExcelToTable() { $('#upload-excel-convert').chang ...

What could be the reason my "mandatory" function is not providing any output?

Recently, I've been working on an Express.js application that handles POST requests with a "city" parameter in the body. The application processes this request and utilizes an external service for further operations. To maintain clean code, I separate ...

Initiate the Html.BeginForm process in an asynchronous manner

Within my ASP.NET MVC 3 application, I am attempting to upload a file using the Html.BeginForm helper, as shown below: <% using (Html.BeginForm("ImportFile", "Home", new { someId = Id }, FormMethod.Post, new { enctype="multipart/form-data" } )) %> ...

Decoding the file's encoding: A beginner's guide

I need help determining the encoding of a file in order to only upload CSV files with utf-8 format. If there are any non utf-8 characters, I want to display an error message. Currently, I am utilizing Papa Parser for parsing. Is there a way to detect the ...

An error was thrown: SyntaxError - { was not expected in script.js on line 5 while checking request

I encountered an issue while executing the code snippet below: var req = new XMLHttpRequest(); req.open('GET', 'data.json'); req.onreadystatechange = function() { if ((req.readyState === 4) && (req.status == 200)) { var cus ...

Receiving an error when trying to access the 'get' property of $http within a nested function

Encountering the following error angular.js:13550 TypeError: Cannot read property 'get' of undefined at Object.DataService.getDataFromAPI I seem to be struggling with the $HTTP.get function. Any insights on what might be going wrong or ...

The PDF file appeared blank after receiving a response from the API using Node.js

When I call a REST API that returns a PDF file, the document appears blank when opened. The console indicates that the data may be corrupted. let url ="API-URL"; var options = { 'method': 'GET', 'url': url ...

Dealing with interstitial advertisements on mobile devices: What is the best approach for handling zoom?

I am facing a challenge with displaying interstitial ads on mobile sites. Different publishers may have varying viewport settings and initial scales on their mobile sites, making it difficult to ensure that the ad appears correctly on all devices with the ...

What is the best way to keep track of the most recent 100 items?

In Angular, I want to store the last 100 items to display. Currently, I am using an array and inserting items with 'array.push'. If this method is not effective for this scenario, what alternative approach can I take? Here is a snippet of the co ...

How to modify the color of a div element with jQuery?

I need some help changing the color of a div with 'jQuery', but I am not sure how to do it. Below is the code I have been trying: function updateDivColor() { $('#OutlineX1').css("color","blue"); } ...

Encountering an error when attempting to access undefined property while using a method as a callback

Exploring OOP and angular is new to me. I am currently trying to implement a reusable table with pagination that triggers an API request when the page changes (pagination within the table component). The issue arises when I attempt to access my method usi ...

Ensure that any modifications made to an Angular service are reflected across all components that rely on that service

I am currently in the process of replicating a platform known as Kualitee.com, which serves as a test-management tool utilized by QA Engineers. Within Kualitee, users can access multiple projects, each containing various test cases and team members. The ab ...

Issue with PassportJS and Express 4 failing to properly store cookies/session data

I have a situation with my Express 4 app using Passport 0.3.2. I've set up a passport-local strategy, and it's successfully retrieving the user information when the /session endpoint is provided with a username and password. The issue arises whe ...

How to smoothly glide to the bottom of a chat box by scrolling synchronously

I am currently in the process of developing a chat application. Each time a user sends a new message, it is added to a list of messages displayed in an unordered list (ul). I have successfully made the ul scrollable, but unfortunately, when a new message i ...

Running a child process within a React application

I'm currently in search of the best module to use for running a child process from within a React application. Here's what I need: I want a button that, when clicked, will execute "npm test" for my application and generate a report that can be r ...

Looking for a solution to split barcode data across two text fields

I am looking to enhance my data input process by utilizing a barcode scanner in conjunction with JQuery. The barcode scanner I have reads both the serial number and model name of each product, but currently displays them together in one text field. Is ther ...

What is the correct way to utilize browser actions for sending keys with the "?" symbol in Protractor?

I'm facing an issue in my tests with a particular line of code browser.actions().sendKeys(Key.chord(Key.CONTROL, '?')).perform(); Interestingly, it works fine with another symbol. For example: browser.actions().sendKeys(Key.chord(Key.CONT ...