SolvedOwlCarousel2 importing 'owl.carousel' with webpack causes Uncaught TypeError: Cannot read property 'fn' of undefined

I am trying to use Owl Carousel in my website managed by webpack and bootstrap3. I installed owlcarousel throughnpm install --save owl.carousel and I import the js file in a typescript file.

When I run gulp to compile the site, I got Uncaught TypeError: Cannot read property 'fn' of undefined

Reproduce problem

  1. In my webpack config.js, I have (all the scripts are in .ts and compiled by webpack)
    module: {
      rules: [
        { test: /\.ts$/, use: 'ts-loader' },
  1. In my main.ts file (entry point), I have
   import * as $ from 'jquery';
   import 'owl.carousel';

I cannot use import $ from 'jquery' as instructed because it causes error TS1192: Module '"jquery"' has no default export.

  1. I have not implemented the carousel in my HTML yet. Just run gulp and I get
Uncaught TypeError: Cannot read property 'fn' of undefined
    at owl.carousel.js:1658
    at Object.<anonymous> (owl.carousel.js:1695)
    at Object.<anonymous> (owl.carousel.js:3273)
    at __webpack_require__ (bootstrap f72d2d9d08115c702cd7:19)
    at Object.<anonymous> (main.ts:13)
    at __webpack_require__ (bootstrap f72d2d9d08115c702cd7:19)
    at bootstrap f72d2d9d08115c702cd7:65
    at bootstrap f72d2d9d08115c702cd7:65
(anonymous) @ owl.carousel.js:1658
(anonymous) @ owl.carousel.js:1695
(anonymous) @ owl.carousel.js:3273
__webpack_require__ @ bootstrap f72d2d9d08115c702cd7:19
(anonymous) @ main.ts:13
__webpack_require__ @ bootstrap f72d2d9d08115c702cd7:19
(anonymous) @ bootstrap f72d2d9d08115c702cd7:65
(anonymous) @ bootstrap f72d2d9d08115c702cd7:65

The error points to line

	$.fn.owlCarousel = function(option) {

Installation reference

https://www.npmjs.com/package/owl.carousel

Related issue

A related issue from slick carousel can be found here. But unfortunately I have to use webpack to serve my site so I cannot "unwrap" owlcarousel from webpack compilation. But I suspect the reason might be similar.

Versions

  • Gulp:
    CLI version 2.0.1
    Local version 3.9.1
  • Webpack
    "webpack": "^2.2.1",
    "webpack-dev-middleware": "^1.10.0",
    "webpack-dev-server": "^2.3.0",
    "webpack-merge": "^2.6.1"
  • typescript/jquery: 2.0.40
  • Owl Carousel: 2.2.0

Update

I got no problem importing is through cndjs, with jquery imported first. So I guess the problem might be the way jquery is handled by webpack or the import * as $ from 'jquery'..

17 Answers

✔️Accepted Answer

You should add this code in your webpack config:

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