4

I am working on a Symfony 5.2.6 project and I am trying to use datatables.net library in my project, but can't find a way to import it properly.

I am using a lot of js/jquery libraries and everything is working well except datatables. (I am using Metronic admin template)

packages.json

This is my webpack.config.js :

const Encore = require('@symfony/webpack-encore');
const CopyWebpackPlugin = require('copy-webpack-plugin');

if (!Encore.isRuntimeEnvironmentConfigured()) {
    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')

    .addStyleEntry('basecss', './assets/sass/style.scss')
    .addStyleEntry('pluginscss', './assets/plugins/plugins.scss')
    .addStyleEntry('extrascss', './assets/css/extras.css')

    .addEntry('app', './assets/app.js')
    .addEntry('plugins', './assets/plugins/plugins.js')
    .addEntry('scripts', './assets/scripts.js')

    .addEntry('test', './assets/test.js')

    .addEntry('page-ms-liste', './assets/pages/matiereseche/liste.js')
    
    .addStyleEntry('page-login-css', './assets/pages/authentication/login.css')

    .enableStimulusBridge('./assets/controllers.json')
    
    .splitEntryChunks()
    
    .enableSingleRuntimeChunk()
    
    .cleanupOutputBeforeBuild()
    
    .enableBuildNotifications()
    
    .enableSourceMaps(!Encore.isProduction())
    
    .enableVersioning(Encore.isProduction())

    .configureBabel((config) => {
        config.plugins.push('@babel/plugin-proposal-class-properties');
    })
    
    .configureBabelPresetEnv((config) => {
        config.useBuiltIns = 'usage';
        config.corejs = 3;
    })

    // enables Sass/SCSS support
    .enableSassLoader()

    .addPlugin(new CopyWebpackPlugin({
        patterns: [
            { from: './assets/images', to: 'images' }
        ],
    }))

    .addLoader({
        test: require.resolve('jquery'),
        use: [{
            loader: 'expose-loader',
            options: {
                exposes: [
                    {
                        globalName: "$",
                        override: true,
                    },
                    {
                        globalName: "jQuery",
                        override: true,
                    }
                ]
            }
        }]})

    .addLoader({
        test: '/datatables\.net.*/',
        use: [{
            loader: 'imports-loader',
            options: {
                imports: {
                    moduleName: 'jquery',
                    name: '$',
                },
                additionalCode: "var define = false;"
            }
        }]})


;
const config = Encore.getWebpackConfig();

module.exports = config;

I also tried to use .autoProvidejQuery()

Inside my scripts.js I have :

window.jQuery = window.$ = require('jquery');
// ...    
require('datatables.net');
require('datatables.net-bs4');

Then in my js file :

var t = $("#datatable");
        t.DataTable(.....)

The error :

Uncaught TypeError: $(...).DataTable is not a function

I found a lot of threads on this topic, but I tried everything without success (using loaders, ...) I also tried to import jquery from CDN and datatables too, but I have a jquery issue (jquery undefined)

If someone has an idea...

Thank you.

NOaMTL
  • 193
  • 1
  • 4
  • 13

2 Answers2

1

Remove

window.jQuery = window.$ = require('jquery');

Then, you can import datatable this way:

import $ from "jquery";
require('datatables.net-bs4')( window, $ );

This way, DataTable should be recognized and you will be able to use it.

Dylan KAS
  • 4,840
  • 2
  • 15
  • 33
  • 2
    i tried to do as you said but I still have issues : `Cannot set property '$' of undefined` (jquery.dataTables.js:132) If I check this file the issue is : `this.$ = function ( sSelector, oOpts ) { return this.api(true).$( sSelector, oOpts ); };` – NOaMTL Apr 13 '21 at 13:36
1

After quite some time testing various answers from Stackoverflow, I managed to make it work (with the help of Guillaume F. and Dylan Kas).

These are the files :

webpack.config.js

const Encore = require('@symfony/webpack-encore');
const CopyWebpackPlugin = require('copy-webpack-plugin');

if (!Encore.isRuntimeEnvironmentConfigured()) {
    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')

     // Main Js file
    .addEntry('app', './assets/app.js')
     
    // In my case Datatable init code is in this file. Don't forget to load this asset from your template page with the shortcut : {{ encore_entry_script_tags('my-page') }}
    .addEntry('my-page', './assets/pages/my-page.js')

    //.. Other imports here ..
    /*.addEntry('scripts', './assets/scripts.js')*/

    .splitEntryChunks()

    .enableSingleRuntimeChunk()

    .cleanupOutputBeforeBuild()

    .enableBuildNotifications()

    .enableSourceMaps(!Encore.isProduction())

    .enableVersioning(Encore.isProduction())

    .configureBabel((config) => {
        config.plugins.push('@babel/plugin-proposal-class-properties');
    })

    .configureBabelPresetEnv((config) => {
        config.useBuiltIns = 'usage';
        config.corejs = 3;
    })
    
    .addPlugin(new CopyWebpackPlugin({
        patterns: [
            { from: './assets/images', to: 'images' }
        ],
    }))

;
const config = Encore.getWebpackConfig();

// Without this, I have issues with my DT.net requires
config.module.rules.unshift({
    parser: {
        amd: false,
    }
});

module.exports = config;

My app.js file

window.jQuery = window.$ = require('jquery');

require('bootstrap');

window.Popper = require('popper.js').default;

// Needed form Datatables Buttons plugin
window.JSZip = require('jszip');
const pdfMake = require('pdfmake/build/pdfmake.js');
const pdfFonts = require('pdfmake/build/vfs_fonts.js');
pdfMake.vfs = pdfFonts.pdfMake.vfs;


require('datatables.net')(window, $);
require('datatables.net-bs4')(window, $);
require('datatables.net-buttons/js/dataTables.buttons.min.js')(window, $);
require('datatables.net-buttons-bs4')(window, $);
require('datatables.net-buttons/js/buttons.flash.js')(window, $);
require('datatables.net-buttons/js/buttons.html5.js')(window, $);
require('datatables.net-buttons/js/buttons.print.js')(window, $);

My packages.json :

{
    "dependencies": {
        // others imports above
        "bootstrap": "^4.6.0",
        "datatables.net": "^1.10.24",
        "datatables.net-autofill-bs4": "^2.3.5",
        "datatables.net-bs4": "1.10.24",
        "datatables.net-buttons-bs4": "^1.7.0",
        "datatables.net-colreorder-bs4": "^1.5.2",
        "datatables.net-fixedcolumns-bs4": "^3.3.2",
        "datatables.net-fixedheader-bs4": "^3.1.7",
        "datatables.net-keytable-bs4": "^2.5.3",
        "datatables.net-responsive-bs4": "^2.2.6",
        "datatables.net-rowgroup-bs4": "^1.1.2",
        "datatables.net-rowreorder-bs4": "^1.2.7",
        "datatables.net-scroller-bs4": "^2.0.3",
        "datatables.net-select-bs4": "^1.3.1",
        "jquery": "^3.6.0",
        "jszip": "^3.5.0",
        "pdfmake": "^0.1.36",
        "popper.js": "^1.16.1",
    },
    "devDependencies": {
        "@symfony/stimulus-bridge": "^2.0.0",
        "@symfony/webpack-encore": "^1.0.0",
        "copy-webpack-plugin": "^8.1.0",
        "core-js": "^3.0.0",
        "expose-loader": "^2.0.0",
        "imports-loader": "^2.0.0",
        "lodash": "^4.17.13",
        "regenerator-runtime": "^0.13.2",
        "sass": "^1.32.8",
        "sass-loader": "11.0.0",
        "script-loader": "^0.7.2",
        "stimulus": "^2.0.0",
        "webpack-notifier": "^1.6.0"
    },
    "license": "UNLICENSED",
    "private": true,
    "scripts": {
        "dev-server": "encore dev-server",
        "dev": "encore dev",
        "watch": "encore dev --watch",
        "build": "encore production --progress"
    }
}

and in the end my file initializing the datatable (I use one entry js file per page): page.js

"use strict";

var MyPage = {
    init: function () {
        const table = $('#datatable').DataTable({
            buttons: [
                {
                    extend: 'print',
                    exportOptions: {
                        columns: [0, 1, 2, 3]
                    }
                },
                {
                    extend: 'excelHtml5',
                    exportOptions: {
                        columns: [0, 1, 2, 3]
                    }
                },
            ],
            columnDefs: [
                {
                    width: '75px',
                    targets: 4,
                },
            ],
        });

        $('#export_print').on('click', function(e) {
            e.preventDefault();
            table.button(0).trigger();
        });

        $('#export_excel').on('click', function(e) {
            e.preventDefault();
            table.button(1).trigger();
        });
    },
};
jQuery(document).ready(function () {
    MyPage.init();
});

Note that in my case I toggle the buttons from 2 html elements.

NOaMTL
  • 193
  • 1
  • 4
  • 13