Vue3 + Vite
Vue3 + Vite
Hello everyone,
I know there are already a few topics about importing DataTables and get it working inside Vue3, but I seem to struggle with the extensions.
So far I successfully imported a module which loads jQuery and Datatables:
# jquery.module.js
import jQuery from "jquery";
Object.assign(window, { $: jQuery, jQuery });
import * as DataTable from "datatables.net-dt";
import "datatables.net-dt/css/jquery.dataTables.min.css";
new DataTable(window, $);
export default window;
In the vite config I added following code (behind the scences it uses rollup.js) to get jquery globally inside my app:
# vite.config.js
build: {
rollupOptions: {
external: ["jquery"],
output: {
globals: {
jquery: "window.jQuery",
jquery: "$",
},
},
},
},
The module is then imported before my vue application:
<!-- index.html -->
<body>
<div id="app"></div>
<script type="module" src="/src/jquery.module.js"></script>
<script type="module" src="/src/main.ts"></script>
</body>
Everything seems good and dataTable is inside my components and successfully renders the table.
<script setup lang="ts">
# component.vue
import { onMounted } from "vue";
onMounted(() => {
$("#example").dataTable();
});
console.log($.fn.dataTable);
But if I want to extend dataTables it simply does not work, eg.:
# component.vue
<script setup lang="ts">
import { onMounted } from "vue";
import "datatables.net-select-dt";
console.log($.fn.dataTable.select.version);
# Console log returns undefined for select object
...
Any ideas? I tried to play around with the rollup and other extensions like buttons etc. but with no success. I know we should use require, but don't know how I can get this working inside my vite build.
Cheers
Hannes
This question has an accepted answers - jump to answer
Answers
Hi Hannes,
I think you'll need to do:
When using CommonJS our libraries return a function as the default export. That function can take parameters should you which to load in jQuery or your own window object. If you don't, then you can just call the function as is.
More information about this available here.
Allan
Awesome @allan works as expected.
As I'm currently doing a full rebuild of my app in TypeScript with node.js backend and vue3 frontend its great that DataTables still works for me. Will save me a lot of time!
Thanks Allan
Hi
I've got this initialization in my vue file
Sadly I can't see the Excel export button and in my package.json I've got this dependencies:
At this point the DataTable is working but I need a Excel button and a action button next to:
Thanks in advance
This doc shows the options available to display the buttons.
{ action: button href, etc.}
won't work in thecolumns
definition. This doc shows how to create custom buttons with theaction
option.Kevin