mkhairi / materialize-sass

Materializecss rubygem for Rails Asset Pipeline / Sprockets
http://materialize.labs.my/
MIT License
806 stars 243 forks source link

Rails Webpacker #190

Open redhoodie opened 5 years ago

redhoodie commented 5 years ago

(This more a n00b question than an issue) How do I use this with webpacker?

What is the equivalent of: //= require materialize

Could you please update the Usage section in Readme.md?

wuworkshop commented 5 years ago

@redhoodie Was wondering the same thing. I think this Medium article does a good job of explaining it:

https://medium.com/@guilhermepejon/how-to-install-materialize-css-in-rails-6-0-0-beta2-using-webpack-347c03b7104e

Jmarques commented 4 years ago

Is it me or since this is an engine this is not compatible with Webpacker? So new default rails app can't use this gem.

aurora-a-k-a-lightning commented 3 years ago

hello :) i think i found a way to use the javascript of this gem in a default rails 6 app.

  1. enable webpacker to use .erb via rails webpacker:install:erb. this will add the line environment.loaders.prepend('erb', erb) to config/webpack/environment.js
  2. rename app/assets/javascript/packs/application.js -> app/assets/javascript/packs/application.js.erb
  3. import materialize.js from the materialize gem into application.js.erb via ruby tags, so the file will look like this

(from a brand new rails app)

// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

import Rails from "@rails/ujs"
import Turbolinks from "turbolinks"
import * as ActiveStorage from "@rails/activestorage"
import "channels"

Rails.start()
Turbolinks.start()
ActiveStorage.start()

// add this line at the bottom! be sure to place any materialize.js api calls after this is loaded
<%= File.read(File.join(Gem.loaded_specs['materialize-sass'].full_gem_path, 'assets', 'javascripts', 'materialize.js')) %>

Now we can use the materialize javascript api like in the documentation!

document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.sidenav');
    var instances = M.Sidenav.init(elems, {}); // M is now defined :)
});

resources: https://edgeguides.rubyonrails.org/webpacker.html https://github.com/rails/webpacker/issues/57#issuecomment-432460683 https://github.com/nathanvda/cocoon/issues/452#issuecomment-384836675