Search code examples
javascriptjqueryecmascript-6datatablesstimulusjs

Problem for using DataTables in Stimulus framework


I use DataTables in webpack ( Stimulus framework ).

I install jQuery and Datatables with yarn:

yarn add jquery --dev
yarn add jszip --dev
yarn add datatables.net --dev
yarn add datatables.net-dt --dev
yarn add datatables.net-buttons-dt --dev
yarn add datatables.net-responsive-dt --dev
yarn add datatables.net-select-dt --dev

Now I create a controller in Stimulus:

import {Controller} from 'stimulus';
import $ from 'jquery';
import 'jszip';
import 'datatables.net';
import 'datatables.net-dt';
import 'datatables.net-buttons-dt';
import 'datatables.net-responsive-dt';
import 'datatables.net-select-dt';

export default class extends Controller {
    connect() {
        $('#data-tables').dataTable();
    }
}

When I open page in console show an error:

Uncaught TypeError: Cannot read property 'ext' of undefined
    at dataTables.buttons.js:42
    at Object.<anonymous> (dataTables.buttons.js:9)
    at dataTables.buttons.js:10
    at Object../node_modules/datatables.net-buttons/js/dataTables.buttons.js (dataTables.buttons.js:30)
    at __webpack_require__ (bootstrap:18)
    at buttons.dataTables.js:8
    at Object../node_modules/datatables.net-buttons-dt/js/buttons.dataTables.js (buttons.dataTables.js:34)
    at __webpack_require__ (bootstrap:18)
    at Module../node_modules/@symfony/stimulus-bridge/lazy-controller-loader.js!./assets/controllers/datatables_controller.js (cmad_lo_controller.js:89)
    at __webpack_require__ (bootstrap:18)

How can I fix this problem?


Solution

  • You must firs install this packages:

    yarn add jquery --dev
    yarn add jszip --dev
    yarn add datatables.net --dev
    yarn add datatables.net-dt --dev
    yarn add datatables.net-buttons --dev
    yarn add datatables.net-buttons-dt --dev
    yarn add datatables.net-responsive --dev
    yarn add datatables.net-responsive-dt --dev
    yarn add datatables.net-select --dev
    yarn add datatables.net-select-dt --dev
    

    Then use this in Stimulus controller:

    import {Controller} from 'stimulus';
    import $ from 'jquery';
    import 'jszip';
    import 'datatables.net-dt';
    import 'datatables.net-buttons-dt';
    import 'datatables.net-responsive-dt';
    import 'datatables.net-select-dt';
    import 'datatables.net-dt/css/jquery.dataTables.css';
    import 'datatables.net-buttons-dt/css/buttons.dataTables.css';
    import 'datatables.net-responsive-dt/css/responsive.dataTables.css';
    import 'datatables.net-select-dt/css/select.dataTables.css';
    
    export default class extends Controller {
        connect() {
            $('#data-tables').DataTable();
        }
    }