Search code examples
ruby-on-railsdatatablesyarnpkgwebpackerruby-on-rails-6

Rails 6 + yarn + datatables issue


I bumped into troubles with webpacker. I'm using Rails 6.beta3 and trying to add Datatables to my app. My steps:

 yarn add datatables.net-dt

then in app/javascript/packs/application.js:

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
import 'bootstrap/dist/js/bootstrap';
import 'popper.js/dist/popper.js';

require( 'datatables.net-dt' )();

config/webpack/environment.js:

const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
module.exports = environment
environment.plugins.append('Provide', new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery',
  Popper: ['popper.js', 'default']
}))

After this if load a page I get an error in js console:

Uncaught TypeError: Cannot set property '$' of undefined
    at DataTable (jquery.dataTables.js:129)

jquery.dataTables.js:

 var DataTable = function DataTable(options) {
    this.$ = function (sSelector, oOpts) { // <---------error is here. Turns out this is not defined variable
      return this.api(true).$(sSelector, oOpts); 
    };

Any ideas? Thanks in advance


Solution

  • Opps. Its my bad. I found the issue. At the end of app/javascript/packs/application.js there was an error. I thought it didn't make impact on overall performance, but after eliminating of this things started working properly.