How to use DataTables with Laravel Vite?

Viewed 511

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();
});
2 Answers

the tricks is DataTable(window, window.$)

The idea is come from 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 give you some hints.

Here's the solution to my problem.

bootstrap.js

import _ from 'lodash';
window._ = _;

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

import DataTable from 'datatables.net';
window.DataTable = DataTable;
DataTable($);

$(document).ready(function() {
    $('#example').DataTable();
});
Related