Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save obonyojimmy/8cf71c7d6342c851c134289f936dca93 to your computer and use it in GitHub Desktop.
Save obonyojimmy/8cf71c7d6342c851c134289f936dca93 to your computer and use it in GitHub Desktop.
DataTables.net with webpack
Here's how to make jQuery DataTables work with npm and webpack. This is the simplest way I found to do it.
See the previous revision of this gist for a way to do it with forcing AMD to be disabled if you need that.
Install DT core: npm install datatables.net
Install a DT style: npm install datatables.net-dt
Then to initialize DT in your app, do this in your main entry point:
// you can use import or require
import dt from 'datatables.net';
import 'datatables.net-dt/css/jquery.datatables.css';
Now you can use .DataTable():
$('table[data-table]').DataTable(); // or whatever you want
@drselump14
Copy link

the latest datatables.net-dt change the css filename into jquery.dataTables.css.
So the code below should work.

import dt from 'datatables.net';
import 'datatables.net-dt/css/jquery.dataTables.css';

@ZackKnopp
Copy link

ZackKnopp commented Apr 18, 2018

Using webpack 4 I needed this in my webpack.config.js:

var webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const BUILD_DIR = path.resolve(__dirname, 'build');
const SRC_DIR = path.resolve(__dirname, 'src');

console.log('BUILD_DIR', BUILD_DIR);
console.log('SRC_DIR', SRC_DIR);

module.exports = {
  entry: {
    app: SRC_DIR + '/app.js'
  },
  output: {
    path: BUILD_DIR,
    filename: 'index_bundle.js'
  },
  mode: 'development',
  devServer: {
    contentBase: BUILD_DIR,
    port: 9000,
    compress: false,
    hot: true,
    open: true
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [ 'style-loader', 'css-loader' ]
      },
      {
        test: /\.(png|jpg|jpeg|gif|ico)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: './img/[name].[hash].[ext]'
            }
          }
        ]
      },
      {
        test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader',
        options: {
          name: './fonts/[name].[hash].[ext]'
        }
      },
      {
        test: /datatables\.net(?!.*[.]css$).*/,
        loader: 'imports-loader?define=>false'
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin(
      {
        inject: true,
        template: './public/index.html'
      }
    ),
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
      'window.jQuery': 'jquery',
      'window.$': 'jquery'
    })
  ]
};

And this where I require() it:

var dt = require( 'datatables.net' )( window, $ );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment