Importing Materialize JS in Webpack with Sage 9

sage9

#1

Hey there. I was able to successfully get Materialize’s SCSS files working in my theme but I’ve really been struggling with getting the JS files set up in Webpack.

Following the instructions here (https://github.com/roots/docs/blob/sage-9/sage/theme-development-and-building.md), I tried:

  1. yarn install materialize-css
  2. In main.js, I added import 'materialize-css/dist/js/materialize'; on line 3.
  3. Ran yarn run build

That seemed to work okay, but there was no directory in dist like the docs said “The dist folder will contain a _/node_modules/ directory that has any assets referenced from your packages.” And when I added the following to the finalize function wrapper in common.js, all hell broke loose:

Materialize.scrollFire([
  {selector: 'img.lazyload', offset: 500, callback: function(el) {
    Materialize.fadeInImage($(el));
  }},
]);

All hell = the error message 'Materialize' is not defined.

Based on @benword’s advice here (Import WOW.js not working correctly with sage 9), I tried importing Materialize into the top of the common.js file. Here’s what I tried, and the corresponding errors I got:

  1. import Materialize from 'materialize-css/dist/js/materialize.js';

Resulting error: common.js:15 Uncaught TypeError: __WEBPACK_IMPORTED_MODULE_0_materialize_css_dist_js_materialize_js___default.a.scrollFire is not a function

  1. import Materialize from 'materialize-css';

Resulting error: common.js:15 Uncaught TypeError: __WEBPACK_IMPORTED_MODULE_0_materialize_css___default.a.scrollFire is not a function

Thanks for any help you can give me! I’m stumped!


#2

Here’s a weird thing. I just searched inside the compiled main.js and see the harmony import for Materialize’s js files is: __WEBPACK_IMPORTED_MODULE_1_materialize_css_dist_js_materialize__

But when I use import Materialize from 'materialize-css/dist/js/materialize'; the error I get is:
Uncaught TypeError: __WEBPACK_IMPORTED_MODULE_0_materialize_css_dist_js_materialize___default.a.scrollFire is not a function

So… different module number. Does that change based on the order of imports?


#3

Welp. After scratching my head and Googling a whole lot more, I found this issue, which seems to indicate the issue is on their end: https://github.com/Dogfalo/materialize/issues/5026

Thanks for being my rubber ducky @JulienMelissas :wink: