Using DataTables with a Webpack Module JS File
Using DataTables with a Webpack Module JS File
I am in the process of changing my JS files into modules to split code up. I currently have a working JS file that uses DataTables, which is imported in via a CDN on the webpage.
I have just changed the script tag for my JS file to be of type="module" and now DataTables no longer works, with the error '$(...).DataTable is not a function'. DataTables is used quite heavily within the page, and has worked until now in terms of ordering of jquery imports etc. Can I not use it with a module JS file?
<head>
{{-- jquery --}}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"
integrity="sha-placeholder" crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"
integrity="sha-placeholder" crossorigin="anonymous">
</script>
{{--
Generate CDN link from https://datatables.net/download/
Attributes added:
- datatables v1.12.1
- buttons v2.2.3
- buttons html5 export v2.2.3
- search panes v2.0.2
- select v1.6.2
--}}
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.12.1/b-2.2.3/b-html5-2.2.3/sp-2.0.2/sl-1.6.2/datatables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.12.1/b-2.2.3/b-html5-2.2.3/sp-2.0.2/sl-1.6.2/datatables.min.js"></script>
</head>
// HTML code
<script type="module" src={{mix("js/posts/post.js")}}></script>
This question has an accepted answers - jump to answer
Answers
You can, but you need to do:
And tell it where to import DataTables from. With a module there isn't a globally registered
DataTable
variable like there is when loading the UMD loader version (.js).If you want to do this without a bundler, have a look at this blog post. Otherwise, you need to use a bundler.
Allan