6

I'm having trouble adding DataTables to my new Laravel 9.21 instance. But I'm getting an error in the console. What am I missing?

Uncaught TypeError: $(...).DataTable is not a function

bootstrap.js

import jquery from 'jquery';
window.jQuery = jquery;
window.$ = jquery;

import DataTable from 'datatables.net';
window.DataTable = DataTable;

$(document).ready(function() {
    $('#example').DataTable();
});
Karl Hill
  • 12,937
  • 5
  • 58
  • 95

3 Answers3

8

The trick is DataTable(window, window.$)

The idea comes from the official doc of datatables.net-bs5. The setup from require( 'datatables.net-bs5' )( window, $ );

My app.js looks like this

import "./bootstrap";
import "../sass/app.scss";

import * as bootstrap from "bootstrap";

import jQuery from "jquery";
window.$ = jQuery;

import DataTable from "datatables.net-bs5";
DataTable(window, window.$);

I hope it gives you some hints.

Karl Hill
  • 12,937
  • 5
  • 58
  • 95
Ken Hui
  • 368
  • 3
  • 17
3

Here's the solution to my problem.

bootstrap.js

import jQuery from "jquery";
window.$ = jQuery;

import DataTable from 'datatables.net';
window.DataTable = DataTable;

$(document).ready(function() {
    $('#example').DataTable();
});
Karl Hill
  • 12,937
  • 5
  • 58
  • 95
1

In my case, just the simple thing worked.

import $ from "jquery";
window.$ = $

import DataTable from 'datatables.net';
window.DataTable = DataTable;

My versions : Vite 4.0.4 and Laravel 9

Linga
  • 10,379
  • 10
  • 52
  • 104