Add owl carousel to your npm project in any way you see fit

After struggling for a while, I finally wanted to implement owl-carousel, but couldn't figure out how to connect it using npm and webpack.

The official NPM website states:

Add jQuery via the "webpack.ProvidePlugin" to your webpack configuration:

const webpack = require('webpack');

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

I already have this configuration in my webpack setup.

Load the required stylesheet and JS:

import 'owl.carousel/dist/assets/owl.carousel.css';
import 'owl.carousel';

First Attempt - Try number 1

Even after changing the CSS file to SCSS, I encountered the following error:

Cannot read property 'fn' of undefined

Second Attempt - Try number 2

Including the imports as stated also resulted in an error:

import 'imports?jQuery=jquery!owl.carousel';

The error message was

Module not found: Error: Can't resolve 'imports' in 'D:\master\my path '

Third Attempt - Try number 3

import owlCarousel from "owl.carousel";

Encountered the same error as in the first attempt.

Review of my webpack.config.js:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const webpack = require('webpack');

let conf = {
    entry: {
        index: "./src/index.js"
    },
    output: {
        path: path.resolve(__dirname, "./dist"),
        filename: "[name]bundle.js",
        publicPath: "dist/"
    },
    devServer: {
        overlay:true
    },
    module: {
        rules: [
            {
                test: /\.js/,
                loader:"babel-loader",
            },
            {
                test:/\.scss$/,
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: [
                        {
                            loader: 'css-loader',
                            options: { 
                                url: false,
                                minimize: true,
                                sourceMap: true
                            }
                        }, 
                        {
                            loader: 'sass-loader',
                            options: {
                                sourceMap: true
                            }
                        }
                      ]
                })
            }
        ]
    },
    plugins: [
        new ExtractTextPlugin({
            filename: "[name].css"
        }),
        new HtmlWebpackPlugin({
            filename: "index.html",
            template: "build/index.html",
            hash: true,
            chunks: ["index"]
        }),

        new webpack.ProvidePlugin({
            '$': "jquery",
            'jQuery': "jquery",
            'Popper': 'popper.js',
            "Bootstrap": "bootstrap.js"
        })
    ]
};

module.exports = (env, options) => {

    let production = options.mode === "production";

    conf.devtool = production ? false : "eval-sourcemap";

    return conf;
} 

In my project, I have two bundles:

index.js

import $ from "jquery";
import jQuery from "jquery";

import "../styles/main/main.scss";
import "normalize.scss/normalize.scss";
import "bootstrap/dist/js/bootstrap.bundle.min.js";

 //in here including  owl-config where I config my owl carousel

import * as owlConfig from "./owl-config";

//after this more js code's

The second bundle is named owl-config.js where all my attempts are made.

My dependencies:

"dependencies": {
    "bootstrap": "^4.1.1",
    "normalize.scss": "^0.1.0",
    "owl.carousel": "^2.2.0",
    "jquery": "^3.3.1",
    "popper": "^1.0.1"
}

Answer №1

The issue arose from my failure to follow the instructions provided in the documentation

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

Here is a snippet from my webpack.config.js

new webpack.ProvidePlugin({
            '$': "jquery",
            'jQuery': "jquery",
            'Popper': 'popper.js',
            "Bootstrap": "bootstrap.js"
        })

This is how I made the necessary adjustments for it to function correctly

new webpack.ProvidePlugin({
            '$': "jquery",
            'jQuery': "jquery",
            'window.jQuery': 'jquery',
            'Popper': 'popper.js',
            "Bootstrap": "bootstrap.js"
        })

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

Attempting to start and restart an asynchronous function using setIntervalAsync results in a TypeError because undefined or null cannot be converted to an

Recently, I've been working on creating a web scraper that utilizes data extracted from MongoDB to generate an array of URLs for periodic scraping using puppeteer. My goal is to make the scraper function run periodically with the help of setIntervalAs ...

React.js pagination - removing empty values from an array

I'm currently working on implementing pagination logic that automatically updates the page numbers when the last index is clicked. For example: 1 2 3 4 5 If a user clicks on the number 5, it should display: 2 3 4 5 6 and so forth... I have succe ...

What is the smallest required version of node and npm needed to run gulp v4.0.2?

After upgrading gulp to version 4.0.2 in one of my projects, I need to update the installation instructions in my README file. Knowing that npm and node are required, I am unsure about the minimum versions needed for gulp v4.0.2 to function properly. I se ...

Invoking res.download() in the Express framework

It's puzzling why this issue is occurring, and it's quite frustrating. I was expecting the file to be downloaded in line with the guidelines provided in the Express documentation. Below is the code snippet I am using: //within React (App.js) ...

Even without using a proxy, I'm encountering errors when trying to install packages through npm

See below for the npm-debug.log output info it worked if the result ends with ok verbose cli [ 'D:\Softwares and Codes\NodeJS\NodeJS\\node.exe', verbose cli 'D:\Softwares and Codes\NodeJS\NodeJS&bs ...

Vue-router is displaying only the root route

I've been working on vue-router for some time now, but I seem to have hit a roadblock. Despite going through numerous articles and documentation, I can't seem to find the solution. Even after reading multiple tutorials on using vue-router, I&apo ...

How to iterate through properties declared in an Interface in Angular 12?

Before Angular 12, this functioned properly: export interface Content { categories: string[] concepts: Topic[] formulas: Topic[] guides: Topic[] } //this.content is of type Content ['formulas', 'concepts'].forEach(c =&g ...

When assigning JSON to a class object, the local functions within the class became damaged

This is a demonstration of Object Oriented Programming in JavaScript where we have a parent Class called Book with a child class named PriceDetails. export class Book { name: String; author: String; series: String; priceDetails: Array<Price> ...

What is the process for implementing a fallback image in Material UI?

Hey there! I'm currently looking to customize the fallback image of a Material UI Avatar with my own original image. Does anyone have any tips on how I can achieve this? const fallbackImage = "../../fallback/img.png" const AvatarWithBadge = ...

Challenge with module declaration in index.d.ts during upgrade from Angular 8 to 9 (excluding Material)

In my index.d.ts file, I have declared two modules like so: declare module 'googlemaps'; declare module 'detect-resize'; Previously, these declarations worked perfectly fine, allowing me to utilize these modules. The googlemaps module ...

npm audit fix --force cannot prevent vulnerabilities from occurring

I find myself in a challenging situation where I am faced with either 22 vulnerabilities or 47. Whenever I try to run npm audit fix, I am always prompted to use the --force switch to actually go through with an upgrade. But upon upgrading, I encounter 22 v ...

Make sure to give an item a little extra attention by highlighting or making it blink after it has

I have a collection of items that I utilize to construct an unordered list using ng-repeat. When a new item is added, I want it to stand out by blinking or having some kind of effect to grab the user's attention. While it would be easy with jQuery, I ...

Drop and drag to complete the missing pieces

Here is a drag and drop fill in the blanks code I created. The challenge I'm facing is that I want users to be able to correct their mistakes by moving words to the right place after receiving points. <!DOCTYPE HTML> <html> <head&g ...

The completion event was not triggered during the AJAX request

I am having an issue with a function that I have created to make an ajax call. Despite using the .done method, it does not seem to be firing as expected. Upon checking my console for errors, I came across the following message: function getIncidentInfo( ...

Utilizing turbolinks enables the page to be reloaded upon form submission

Currently, I have implemented turbolinks in my Rails application. However, every time I submit a form, the page reloads and the form is submitted. Is there a way to prevent the page from reloading and also submit the form seamlessly? ...

Searching for $or command in express.js

Is it possible to use $or in the app.get() function of an express.js application? For example, how would I write a find() query that includes $or like this: db.inventory.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } ) I'm curious about ...

retrieving a URL with the help of $.getJSON and effectively parsing its contents

I seem to be struggling with a coding issue and I can't quite figure out what's wrong. My code fetches a URL that returns JSON, but the function is not returning the expected string: function getit() { var ws_url = 'example.com/test.js&ap ...

The Vue.js application is experiencing issues with displaying Google Maps functionalities

I have developed an application using Vue.js in Monaca and Cordova with onsenUI. My goal is to display my location on a Google map within the page. I attempted to achieve this by utilizing the npm package named vue2-google-maps, but unfortunately, it' ...

Discovering the art of interpreting the triumphant outcome of an Ajax request with jquery/javascript

I recently encountered a challenge with my function that deals with a short JSON string: <script id="local" type="text/javascript"> $( document ).ready(function() { $('tr').on('blur', 'td[contenteditable]', functi ...

AngularJS is failing to recognize the onload event when loading a URL

I am currently working with the AngularJS Framework and I have encountered an issue. My directive only seems to work when the window is fully loaded. screensCreators.directive('createscreen', function () { return { restrict: "A", ...