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

Wrap each object in a container and then insert its key and values into that container using jQuery

How can I wrap each item and then insert the object's indexes and values into each created wrapper? I've attempted to accomplish this using the following code: $.ajax({ url: "some url", type: "GET", success: function(data) { var data ...

What is the best way to programmatically route or navigate to a specific route within a Next.js class component?

tag: In the process of creating my app with next.js, I primarily use functional components. The sole exception is a class component that I utilize to manage forms. Upon form submission, my goal is to redirect back to the home page. However, when I attemp ...

Reactivity in Vue not responding when listening from a different object

Can someone help me understand why my Vue object is not reactive to changes in another object? See the code snippet below. exampleObject = { exampleProperty: null } exampleObject.update = function () { this.exampleProperty = 'updated data&apo ...

Tips for utilizing the useState Hook in NextJs to manage several dropdown menus efficiently:

Currently, I am in the process of designing an admin panel that includes a sidebar menu. I have successfully implemented a dropdown menu using the useState hook, but it is not functioning exactly as I had envisioned. My goal is to have the if statement onl ...

Switching between a secondary menu using ClassieJS or jQuery?

Currently, the code is configured to toggle the same menu for every icon. To see my current progress, you can check out this fiddle: http://jsfiddle.net/2Lyttauv/ My goal is to have a unique menu for each individual icon. I began by creating the followi ...

Inserting a line break in real-time within a JSX statement

Currently working on a React application that retrieves song lyrics from an API. The API provides me with a lyrics_body attribute as a string, which I use to showcase the lyrics on the webpage. However, when React renders it, the format is not ideal becau ...

Utilizing the Filter Function to Eliminate an Element from an Array

I am a beginner in the world of React and I'm currently working on developing a simple timesheet tool where users can add tasks and save them. My tech stack includes React and Typescript. Currently, my main component has an empty array for tasks and ...

Merge functions that execute identical operations

I find myself in a situation where I have two functions that do very similar tasks, but on different elements. Initially, I only anticipated having these two functions, but now I realize I'll need to add more. This will result in a lot of repetition. ...

Tips for preserving the installation of a global package by utilizing the package.json file

Is there a way to save the installation of a global package using package.json? I've come up with a method that works for me: Here's what I added to my package.json: "scripts": { "preinstall": "npm install babel babel-cli -g" }, This scri ...

Creating distinct web addresses for various sections of vue.js pagination

I've implemented pagination using vue.js for my website's gallery. However, I'm facing an issue where the URL doesn't change when navigating through pages and upon page refresh, it always resets to page 1. My goal is to have the URL ref ...

Error in Browserify Express App: Unexpected token while parsing the file

I have been attempting to browserify a javascript file. When I run the command: browserify global.js -o bundle.js An error message is returned: Error: Parsing file C:\ocquiz\public\javascripts\global.js: Unexpected token (756 ...

Is there a way to configure json-server, when utilized as a module, to introduce delays in its responses

json-server provides a convenient way to introduce delays in responses through the command line: json-server --port 4000 --delay 1000 db.json However, when attempting to achieve the same delayed response using json-server as a module, the following code ...

What is preventing me from executing this function more than once?

Having this function: const sliderTextChange = document.getElementsByClassName('slider') // text change const changeSliderText = change => { const sliderLeft = document.getElementsByClassName('switch-left') const sliderRight = ...

Troubleshooting npm package problems during lighthouse installation

I'm attempting to set up the lighthouse tool in my terminal by running npm install -g lighthouse However, I encounter an error message. Note: "<user-name" is used as a placeholder for my username (base) X-136:~ <user-name>$ npm ins ...

What is the best way to enter text into the terminal following the execution of "yarn start"?

While developing a Node chat application, I encountered an issue where I am unable to type anything in the terminal after entering "yarn start". The tutorial I am following shows that the instructor can still input commands in their terminal after running ...

TypeScript is unable to recognize files with the extension *.vue

Can someone assist me with an issue I'm facing in Vue where it's not detecting my Single File Components? Error message: ERROR in ./src/App.vue (./node_modules/ts-loader!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/Ap ...

GraphQL Error (Status Code: 429) - Next.js Development issue

If you're facing a GraphQL Error (Code: 429) while working on a nextjs project, here's a handy solution. Here's what happened: I created a headless CMS using Hygraph and NextJS 13 for a blog project. I also utilized the npm package graphql ...

An undefined value error occurred while attempting to save data to a MongoDB collection through a node/express server

Anticipated Outcome I am looking to successfully save a new page to mongo db after server validation of input, without encountering any errors in the console. The issue seems to be originating from the post method in the routes in admin_pages.js and I&apos ...

Establishing the preset values for Material-UI toggle button group

I utilized the Material UI library to implement a button toggle widget for selecting options. Check out my codesandbox project here - https://codesandbox.io/s/50pl0jy3xk The user can interact by choosing a membership type: adult, child, or infant. Option ...

Adjust the value of a JavaScript variable using Selenium

My dilemma involves a boolean JavaScript variable called foo, which is currently set to true but I need it changed to false. This particular variable has the advantage of having global scope. When using Selenium, what is the most effective method for alte ...