Initializing DataTable in javascript without the jQuery object
Initializing DataTable in javascript without the jQuery object
This seems so simple, and I'm pretty sure it was working at one point, which makes me think there's a conflict with another library. It's a stimulus controller, and I'm using webpack.
I'm never quite sure when to use import v require, so it could be that, too. Or perhaps something to do with jQuery?
const DataTable = require('datatables.net');
import ('datatables.net-bs5');
let dt = new DataTable('#table', {...});
Uncaught (in promise) ReferenceError: DataTable is not defined
at ./node_modules/@survos/grid-bundle/src/controllers/grid_controller.js (grid_controller.js:24:1)
at Function.webpack_require (bootstrap:19:1)
Answers
Why are you using
require
for thedatatables.net
package andimport
for thedatatables.net-bs5
package? I'd suggest being consistent and use the same for both. Also, exactly how they should be used will depend on how Webpack is configured - for ESM or CommonJS.If you are able to use StackBlitz or similar to put a little example together based on your WebPack configuration, I should be able to show how it can be done.
Allan
Even eliminating the additional bs5 library, neither of the following lines work:
I use encore for my webpack config, with autoProvidejQuery set to true, but turning it off doesn't change anything.
I'm not sure how to use StackBlitz to include a package.json and webpack.
I'm 99% certain that this used to work, so it's possible that something changed with webpack-encore
Try:
The default export for the ES module is the DataTables base object.
The other thing to do would be to:
and show me the result. That will hopefully tell me what mode the library is being loaded in.
Allan
On a possibly related note, since the release of 1.13, is the yarn section on https://datatables.net/download/#Step-3.-Pick-a-download-method still the best approach? That is, to use require()?
Possibly! It depends on if you are using a bundler. See this part of the 1.13 release blog.
Allan
I have read, and re-read, the blog post. I'm still stuck. I've put together a github repo with a minimal setup that perhaps can help with showing the problem. I'll open a new discussion for that.
Is it DataTable, or DataTables? Both these lines seem to work.
import DataTables from "datatables.net-bs5";
import DataTable from "datatables.net-bs5";
Doesn't matter. That is just importing the
default
export so you could do:```js
import Bananas from 'datatables.net-bs5';
````
And
Bananas
would then be your DataTables variable. Only if you put braces around the variable name does it need to match something that is exported by the library.It looks like this thread is your continuation of this discussion. I'll switch over to that.
Allan