claviska / jquery-minicolors

jQuery MiniColors Plugin
MIT License
956 stars 312 forks source link

How to import minicolors with webpack? #275

Closed zedtux closed 5 years ago

zedtux commented 5 years ago

After having added this projet to my Angular app using yarn, I have the following error :

TypeError: element.minicolors is not a function

Looking around in the code, and especially to the UMD, it seems to me that I should find a way to get it loaded as a CommonJS module so using the Webpack imports-loader I'm trying to do so but I can't figure out how to perform this.

Before to open this issue here, I have asked on SO but I had no luck yet.

Thank you.

claviska commented 5 years ago

I don't usually use jQuery with a module loader, but perhaps the suggestions in this answer will point you in the right direction.

Another thing that may (or may not) help is aliasing window.jQuery like I've seen in a number of Bootstrap projects.

new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery',
  'window.jQuery': 'jquery'
})

Aside from that, I'm not sure as it could be an Angular thing, a Webpack thing, or simply an error in your code. Try logging the value of $ or jQuery where you instantiate and see if they're actually references to jQuery.

zedtux commented 5 years ago

Thank you @claviska for your quick response.

I tried everything from the SO question you shared but it didn't worked. I also tried the alias you gave, but still not working.

From the Chrome console I can access $ and I'm using the fullcalendar package which depends on jQuery so I think jQuery is well configured.

zedtux commented 5 years ago

After facing the same kind of issue with the fullcalendar jQuery plugin, banging my head to the wall for few seconds and I found a way to load jQuery plugins using the script-loader and the expose-loader !

The fullcalendar plugin uses jQuery and moment so I had to expose them as global :

environment.loaders.append('jquery', {
  test: require.resolve('jquery'),
  use: [
    {
      loader: 'expose-loader',
      options: 'jQuery'
    },
    {
      loader: 'expose-loader',
      options: '$'
    }
  ]
})

environment.loaders.append('moment', {
  test: require.resolve('moment'),
  use: [
    {
      loader: 'expose-loader',
      options: 'moment'
    }
  ]
})

And then I can load fullcalendar this way :

environment.loaders.append('fullcalendar', {
  test: require.resolve('fullcalendar'),
  loader: 'script-loader?fullcalendar/dist/fullcalendar.js'
})

So I did the same with jquery-minicolors :

environment.loaders.append('jquery-minicolors', {
  test: require.resolve('jquery-minicolors'),
  loader: 'script-loader?jquery-minicolors/jquery.minicolors.js'
})

And It works 🎉.