Cannot use DataTables at all: got Uncaught ReferenceError: require is not defined
Cannot use DataTables at all: got Uncaught ReferenceError: require is not defined
I'm trying to use DataTables 2.0.2 in PHP project. I tried to install DataTables by various ways which described in manual: by Composer
composer require datatables.net-bs5
or CDN or local installation — download files and put them outside of vendor
direcrory — all results are the same.
I use jQuery 3.6.0 which is included before DataTables
<script src="/jquery/jquery.min.js"></script>
</head>
<body>
<!-- ••• -->
<table class="table table-striped data-table">
<!-- ••• -->
<script src="/jquery/datatables/datatables.js"></script>
<script>
$(document).ready(function () {
$('.data-table').DataTable();
});
</script>
</body>
Full version of datatables.js
is used instead of minified one for debug purposes.
I see errors and warning in browser’s console:
Uncaught ReferenceError: require is not defined
at datatables.js:48:12
at datatables.js:73:2
jQuery.Deferred exception: $(...).DataTable is not a function TypeError: $(...).DataTable is not a function
at HTMLDocument.<anonymous> (http://172.28.0.3/attestation/vendors.php:273:30)
at e (http://172.28.0.3/jquery/jquery.min.js:2:30038)
at t (http://172.28.0.3/jquery/jquery.min.js:2:30340) undefined
jquery-3.6.0.js:4059 Uncaught TypeError: $(...).DataTable is not a function
at HTMLDocument.<anonymous> (vendors.php:279:30)
at e (jquery-3.6.0.js:3766:29)
at t (jquery-3.6.0.js:3834:12)
datatables.js:48 is
var jq = require('jquery');
vendors.php:279 output is
$('.data-table').DataTable();
Google Chrome 122.
Is it DataTables bug or I’m doing something wrong? I tried to remove all scripts and styles except DataTables, Bootstrap and jQuery as well as unnecessary HTML elements — this minified example works well, see https://live.datatables.net/lubidage/1/
This question has an accepted answers - jump to answer
Answers
The error suggests that the CommonJS loader is being used. Do you have an object called
exports
on the page somewhere? Or perhaps composer is injecting one? You could check by doingconsole.log(exports)
just before you load the DataTables JS. Then if you could show me the output in the console please?Allan
Yes, you are right — this page contain
exports
— it printed with white background:Should I remove this object?
I found this list and tried to remove it and related script
Now DataTables is working well. Thank you!
Now that is interesting! I've never encountered quite that issue before, but having seen it, I'm somewhat surprised that this is the first time! I'll change my loader code to allow for such cases in future.
Regards,
Allan