DataTables of Bootstrap4 with WebPack is not integrated in Rails 6?

Anyone here answer this question?

Also answered on StackOverflow.

I’m not sure if it’s a typo, but your webpack directory is spelled incorrectly: webapck vs webpack.

I’m exposing jquery a little differently than you. This is with expose-loader 1.0 syntax: config/webpack/environment.js

environment.plugins.prepend('Provide', new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery',
  jquery: 'jquery', 
})
)

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

Speaking of which, I have expose-loader explicitly included in package.json. I don’t think any of the Rails webpacker packages include it by default.

    "@rails/webpacker": "5.1.1",
    "bootstrap": "^4.3.1",
    "datatables.net-bs4": "^1.10.19",
    "expose-loader": "^1.0.0",
    "jquery": "~3.4.1",
    "popper.js": "^1.15.0",

I do not have the config/webpack/loaders/datatable.js file at all.

In app/javascript/packs/application.js I do not import/require jquery at all, that is loaded globally with the above config.

import 'bootstrap'
require('datatables.net-bs4')

app/views/whatever.html.erb

...
<script>
	$('#assignments_table').DataTable({
		paging: false, 
		language: {
			emptyTable: "No assignments entered",
		},
	});
</script>

I am using Datatables with Rails 6, Bootstrap 4 and Webpack. I was fighting with it for about a day. I remember it was full or errors and things were not working out. This ’ $(…)DataTable is not a function’ was though.

My fight was kind of absurd. I was using jQuery 2 because of another dependency that was requiring jQuery 2. The problem was that datatables was trying to load jQuery and if there was no jQuery, or there was jQuery 1 or jQuery 2, it was loading jQuery 3 (I don’t know why, it just silently did). So I ended up with two jQuery(s). 2 and 3. I was using 2 everywhere and 3 was loaded by datatables and datatables was attaching to 3. But then the one that was exposed was jQuery 2 and there was no .DataTable method attached to jQuery 2.

This was a really hard to debug problem. So hard that finally I re-wrote the dependency that was requiring jQuery 2 and migrated it to jQuery 3 (I was going to do it in a few months anyway).

What I am sharing is my current configuration that makes datatables work.

# app/javascripts/packs/entry_point.js
require('datatables.net');
# config/webpack/environments.js
environment.plugins.prepend(
  'Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery'
  })
)
environment.loaders.append('expose', {
  test: require.resolve('jquery'),
  use: [{
    loader: 'expose-loader',
    options: '$'
  }, {
    loader: 'expose-loader',
    options: 'jQuery',
  }]
})

Then in a Stimulus controller I can do

    const table = $(`${tableIdentifier}`).DataTable({