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"
}