Symfony 6 - Webpack Encore - DataTable is not a function

Symfony 6 - Webpack Encore - DataTable is not a function

CrawCraw Posts: 3Questions: 1Answers: 1

Hi, I'm trying to use DataTables in my symfony 6 project with webpack encore, but I'm facing some issues.

First I installed those packages:

yarn add datatables.net
yarn add datatables.net-bs5

Then in my app.js:

import '../scss/app.scss';

const $ = require('jquery');

require('bootstrap');
require('datatables.net');
require('datatables.net-bs5');

$(document).ready(function() {
$("#myTable").DataTable();
});

But I got this issue, .DataTable is not a function, can someone help me?

PS: Sorry for my english

Craw

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,535Questions: 1Answers: 10,475 Site admin

    Hi Craw,

    Try this please:

    require('datatables.net')(window, $);
    require('datatables.net-bs5')(window, $);
    

    It does depend a little bit on if Webpack is configured for ES modules or CommonJS - that is the CommonJS syntax which matches the require code you have above.

    Allan

  • CrawCraw Posts: 3Questions: 1Answers: 1

    Hey, thanks for answer, I already tryed and it show this error:

    Uncaught TypeError: webpack_require(...) is not a function

    And can u tell me how to make code snipet in this forum?

  • CrawCraw Posts: 3Questions: 1Answers: 1
    Answer ✓

    Soluce :

    Jquery was on my nodes_modules and I was abble to use it normaly in my app.js so I thought it was not necessary to install the package. It was a mistake after I :

    yarn add jquery

    This code work great

    const $ = require('jquery');
    require('bootstrap');
    require('datatables.net');
    require('datatables.net-bs5');

    $(document).ready(function() {
    $("#myTable").DataTable();
    });

    You have to disable autoprovide jquery in webpack config

  • allanallan Posts: 63,535Questions: 1Answers: 10,475 Site admin

    Awesome - thanks for the update.

    Allan

  • paskuale75paskuale75 Posts: 5Questions: 0Answers: 0

    Hi, thanks for the great information, may I ask why you use require instead of import statement ?

  • allanallan Posts: 63,535Questions: 1Answers: 10,475 Site admin

    They might be using CommonJS rather than ES Modules. DataTables supports both. Indeed in a lot of cases, a packager such as Webpack can take ES Module syntax (import ...) and down convert it back to CommonJS and work from there without you ever knowing, It depends on how Webpack is configured.

    If you are starting on a new code base, I'd suggest going with ES Modules. Only use CommonJS if you are working on an older code base that already uses it.

    Allan

Sign In or Register to comment.