Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Materialize jQuery functions not working in Webpack application

I recently migrated my project from Meteor to Webpack and am experiencing errors when trying to use Materialize.css to build my UI. The custom materialize functions, such as $(...).tooltip, causes an Uncaught TypeError to be thrown in the console. This does not allow me to use Materialize in my app.

Anyone else experience these kinds of errors when trying to use Materialize in a webpack application? Any direction on how to solve these problems would be much appreciated. Thanks!

The code I use to load the Materialize module and its dependencies in the index.js at the root of the directory is below.

index.js:

import 'materialize-loader';
import 'materialize-css/dist/css/materialize.css';
window.jQuery = require('jquery');
window.$ = require('jquery');
import 'materialize-css/dist/js/materialize.js';
import 'materialize-css/js/init.js';
like image 869
Trey Granderson Avatar asked Dec 09 '16 22:12

Trey Granderson


1 Answers

Struggled with the same issue. What you need to do is to make following modification in your webpack config:

const webpack = require("webpack");

in the options for exports add:

plugins: [
     new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            "window.$": "jquery",
            "window.jQuery": "jquery"
    }),

Also, remove the following statements from index.js:

import 'materialize-loader';
window.jQuery = require('jquery');
window.$ = require('jquery');
import 'materialize-css/js/init.js';

Note: I tested this for webpack 4+; not sure if it'll work for other versions.

Plausible explanation: The js file for materialize plugin probably uses window.$ or window.jQuery for jquery methods and probably you have to give a global alias for the same in your webpack config.

like image 84
Umang Khandelwal Avatar answered Oct 23 '22 10:10

Umang Khandelwal