16

I am trying to use datatables JQuery plugin with webpack and typescript. I already have JQuery up and running together with typings (intelliSense works), for datatables I have the intelliSense only, but after webpack build when I run the app the code fails when it comes to $('#id').dataTable() line.

app.js:43Uncaught TypeError: $(...).dataTable is not a function

I am not able to figure out how to attach this pluggin correctly, can anyone please help me?

The webpack.config.js is as follows; https://gist.github.com/marcingolenia/2fa78ed2cd42f9294da5edd22d351245

I hope this line will solve the problem;

{ test: require.resolve("dataTables.net"), loader: "imports?define=>false,$=jquery"},

as the doc of import loader says;

There are many modules that check for a define function before using CommonJS. Since webpack is capable of both, they default to AMD in this case, which can be a problem if the implementation is quirky.

datatables provides both, so I wanted to disable AMD using define=>false as mentioned here https://www.datatables.net/forums/discussion/32542/datatables-and-webpack

Now I'm stuck :(

Jinx
  • 348
  • 3
  • 14
  • Have you installed the jquery datatables typings? – thitemple Apr 22 '16 at 12:31
  • Yes, the typings are there so the intellSense for $(...).dataTable is working well and typescript compiler do not show any erros. this comes from my typings; `"jquery": "registry:dt/jquery#1.10.0+20160316155526", "jquery.datatables": "registry:dt/jquery.datatables#1.9.4+20160317120654"` – Jinx Apr 22 '16 at 12:43

3 Answers3

11

You are almost there!

Make sure both datatables.net and datatables.net-dt installed via NPM:

npm install datatables.net datatables.net-dt --save-dev

in your entry file ./src/main.js write:

require( 'datatables.net' )( window, $ )
require( 'datatables.net-dt' )( window, $ )

after that, any code logic of following format $(...).DataTable will work as the examples shown on the DataTables' homepage.

dlkulp
  • 2,204
  • 5
  • 32
  • 46
Sitian Liu
  • 1,156
  • 10
  • 14
5

Disabling AMD seems to be the answer. Many of the solutions I found weren't working for me.

The simplest way to disable AMD is to add the following rule to your webpack config(webpack 2+)

module: {
    rules: [
        { parser: { amd: false } }
    ]
}
Matt B
  • 109
  • 2
  • 2
1

Disabling AMD solve this issue for me. Here is how to disable AMD if you are using Webpack Encore in Symfony 4:

var config = Encore.getWebpackConfig();

// disable amd, for datatable
config.module.rules.unshift({
  parser: {
    amd: false
  }
});

module.exports = config;
sunix
  • 146
  • 1
  • 8