How to use rails webpack loaded js in js erb template - ruby-on-rails

I am using webpacker gem in rails 5.0 app, but I can't get the javascript to execute/be available in the js.erb I'm hitting on validation error. I'm sure that I'm violating some simple premise here, but can't find the answer and no compile or console errors are present. I do have the <%= javascript_pack_tag 'application' %> in my application.html.erb
Here is the setup:
app/javascript/packs/application.js:
import * as CustomerSession from 'customer_sessions';
console.log('Hello World from Webpacker');
app/javascript/customer_sessions/index.js:
export { univgwTabs } from './univgwTabs';
app/javascript/customer_sessions/univgwTabs:
export let univgwTabs = () => {
console.log('hi');
};
js erb template called on validation error of form:
$("#right_side_right_bottom_target").html("<%= j render partial: 'generic_object_new' %>");
CustomerSession.univgwTabs();
Global.resizeWindow();

If there is no issue with console.log(CustomerSession) in the location where you are importing it then the simplest fix I found was to just assign the imported variable as one of the global windows properties.
// in packs/application.js (or wherever your pack is)
// import
import * as CustomerSession from 'customer_sessions';
// assign
window.CustomerSession = CustomerSession
Assuming that there is no issues with webpacker, you should now be able to console.log(CustomerSession) in the console or your js.erb file.

Related

How to call a javascript function inside a rails view?

I did just a upgrade from RAILS 5 to RAILS 6 and I see that all rails views are not able to call a javascript function as before in RAILS 5.
I have an external javascript file located under
app/javascript/packs/station.js
This is is embeded in in app/views/layouts/application.html.erb as
<%= javascript_pack_tag 'station' %>
This is the code how I call the javascrpt function from html.erb file :
<%= text_field_tag(:station_text_field, ... ,
onkeyup: "javascript: request_stations(); ") %>
When I try to call a function thats is part of the station.js then I get an error in the browser developmer view: ReferenceError: request_stations is not defined
But I can also see in the brwoser view, under Debugger :
Webpack / app/javascript / packs / station.js
and the javascript function I want to call.
So it seems that this script was loaded by the browser.
In contrast, when I just copy and paste these few lines that represent this javascript function direct into the template view file (...html.erb), something like :
<script>
function request_stations ()
{
alert("calling request_stations");
};
</script>
then - it works as expected !
By default, variables/functions defined inside JavaScript files that are packed by Webpacker will not be available globally.
This is a good thing, because it prevents global naming conflicts. Generally speaking, you don't want to reference javascript functions/variables from your view. You instead want to write JavaScript in a way that attaches functionality to DOM nodes using their id or other attributes.
Here is a basic example based on the code you provided:
# in your rails view
<%= text_field_tag(:station_text_field, ..., id: 'station-text-field') %>
// in your javascript
function request_stations() {
alert("calling request_stations");
};
const stationTextField = document.querySelector("#station-text-field");
stationTextField.addEventListener('keyup', (event) => {
request_stations();
});
Agree with mhunter's answer.
This post helped me get a grounding on this difference in Rails 6: https://blog.capsens.eu/how-to-write-javascript-in-rails-6-webpacker-yarn-and-sprockets-cdf990387463
What I don't see in your question is whether or not you did this in app/javascript/packs/application.js:
require("#rails/ujs").start()
require("turbolinks").start()
require("#rails/activestorage").start()
require("channels")
require("station")
The big difference in Rails 6 is that you have to deliberately:
require a JS file
deliberately export something from that file
deliberately import that something, in the file where you want to use it.
So if there is a function in station.js that you want to use, connect the steps above. Start with a simple function in station.js that fires upon DOMContentLoaded, and add a console.log("hey, station.js is alive and well"). If you don't see it, then something in those 3 steps is not right.
In pre-Rails6, you had a "garden" of JavaScript, just by virtue of being in the asset pipeline. In Rails 6, you have to be more deliberate.

Cannot get styles to load with Rails 5 & vue2-dropzone

I'm trying to get vue2-dropzone (version 3.0.3) to cooperate nicely with my Rails 5.1.4 app. I've added Dropzone to to my form and loaded the module but somehow I am not able to see the default styles. I don't think this is a problem with vue2-dropzone as much as with how webpacker loads the css.
My current setup:
application.js
import vue2Dropzone from 'vue2-dropzone'
import 'vue2-dropzone/dist/vue2Dropzone.css'
const myForm = new Vue({
el: '#multistep-form',
components: {
vueDropzone: vue2Dropzone
},
data: function () {
return {
dropzoneOptions: {
url: 'https://httpbin.org/post',
thumbnailWidth: 150,
maxFilesize: 5,
dictDefaultMessage: "<i class='fa fa-cloud-upload'></i> Drop files here to upload",
headers: { "My-Awesome-Header": "header value" }
}
}
}
and my _form.html.erb partial:
<vue-dropzone ref="myVueDropzone" id="dropzone" :options="dropzoneOptions">
</vue-dropzone>
I see that the Dropzone form is loaded. However, I cannot see the default style. I see the following in the console when I run :
Child extract-text-webpack-plugin node_modules/extract-text-webpack-plugin/dist node_modules/css-loader/index.js??ref--1-2!node_modules/postcss-loader/lib/index.js??ref--1-3!node_modules/vue2-dropzone/dist/vue2Dropzone.css:
[0] ./node_modules/css-loader?{"minimize":false,"sourceMap":true,"importLoaders":2}!./node_modules/postcss-loader/lib?{"sourceMap":true,"config":{"path":"/Users/myuser/Documents/apps/myapp/.postcssrc.yml"}}!./node_modules/vue2-dropzone/dist/vue2Dropzone.css 30.5 kB {0} [built]
I don't think it's an error since it says webpack: Compiled successfully. but I do think that webpack isn't loading vue2Dropzone.css for some reason. How should I configure webpacker to load that css file?
If I put the css file manually into my app/assets/stylesheets/ then it works without a problem.
Thanks in advance!
I think your CSS file should be loaded in CSS and not in js.
Here's how I'm doing it in my project.
Create application.css in packs folder and import into the Rails layout file, application.html.erb
<%= javascript_pack_tag 'application' %>
#import 'vue2-dropzone/dist/vue2Dropzone.css'
If you do this though, you will get an error because #import is a sass syntax. So you will need to do some extra webpack config.
You will find this post useful if you want to use css inside the application.js file.
https://medium.com/#mayorsan/rails-angular-webpacker-gem-like-a-pro-7cf40a588ab9

React Rails Component is not defined

I'm trying to get the react-rails gem (version 2.1) working in my Rails 4.2.4 app. I've gone through the setup steps in the Readme and I'm using webpacker for the js preprocessing. I have a component inside of app/javascript/components/label.js that looks like this:
import React, {PureComponent} from 'react';
import ReactDOM from 'react-dom'
export default class Label extends PureComponent {
render () {
return (
<div>Something rendered in React</div>
)
}
}
And then I reference this in my view with the following line:
= react_component("Label")
As far as I can see from the Readme, this should be all that is necessary in order to render the component (provided the application pack is included in the layout, which it is)
= javascript_pack_tag 'application'
So I'm confused as to why I'm getting the error in my browser that the component is not defined.
Uncaught ReferenceError: Label is not defined
Opening app/javascript/packs/application.js I can see the following:
console.log('Hello World from Webpacker')
// Support component names relative to this directory:
var componentRequireContext = require.context("components", true)
var ReactRailsUJS = require("react_ujs")
ReactRailsUJS.useContext(componentRequireContext)
First I verified that the console log is displayed in the browser (it is). I'm not sure what componentRequireContext does, but if it is relative to the current file, then it seems odd that it points to components and not ../components, but changing this doesn't render the component. However, I can get the component rendering if I add the following line:
window.Label = require('../components/label.js');
I thought the React Rails gem took care of this though, provided the components were saved in the app/javascript/components directory? There's nothing in the Readme that says that I need to explicitly declare and require the component, or am I mistaken?
It looks like you have a capitalization issue. You named the file 'label.js' but you are looking for '= react_component("Label")' So it looks and doesn't find what Label is. Then when you set Label on the window then react is like "Oh ok, Label is actually label.js." and it does stuff. TLDR capitalization matters.

Dynamic CSS using Sprockets

I'm working on a site builder in rails and I would like to render the sites css using Sprockets SCSS processors. Since the user can change colors and logos, I can't use Sprockets precompilation so I've started working on a Rails SCSS template handler to handle dynamic views.
The goal is to compile 'app/views/sites/show.css.scss' any time /sites/43543.css is requested. Here's what I have so far. You'll notice I first run the template through the ERB processor and then attempt to run it through Sprockets.
https://gist.github.com/3870095
Manuel Meurer came up with an alternative solution that writes the ERB output to a path and then triggers the Asset Pipeline to compile it. I was able to get his solution to work locally but it wont work on heroku because the asset path is not writable. Files can only be written to the tmp directory and those files are only guaranteed for a single request.
http://www.krautcomputing.com/blog/2012/03/27/how-to-compile-custom-sass-stylesheets-dynamically-during-runtime/
After a long day I was able to solve my problem thanks to John Feminella and his post on google. The challenging part for me was figuring out how to create a new Sprockets::Context. Luckily John's solution doesn't require a Context.
Updated gist here
Attempt #1
This code does not allow importing css files from the asset pipeline.
#import "foundation"; works because foundation is loaded as a compass module
#import "custom_css"; results in an error message saying the file could not be found
def call(template)
erb = ActionView::Template.registered_template_handler(:erb).call(template)
%{
options = Compass.configuration.to_sass_engine_options.merge(
:syntax => :scss,
:custom => {:resolver => ::Sass::Rails::Resolver.new(CompassRails.context)},
)
Sass::Engine.new((begin;#{erb};end), options).render
}
end
Attempt #2
This code fails to embed base64 urls using asset-data-url
def call(template)
erb = ActionView::Template.registered_template_handler(:erb).call(template)
%{
compiler = Compass::Compiler.new *Compass.configuration.to_compiler_arguments
options = compiler.options.merge({
:syntax => :scss,
:custom => {:resolver => ::Sass::Rails::Resolver.new(CompassRails.context)},
})
Sass::Engine.new((begin;#{erb};end), options).render
}
end
Attempt 3
Turns out you can use empty values while creating the context. Code below works in development but throws an error in production.
ActionView::Template::Error (can't modify immutable index)
It appears the error occurs in Sprockets::Index which is used instead of Sprockets::Environment in production. Switching to Sprockets::Environment doesn't solve the problem either.
def call(template)
erb = ActionView::Template.registered_template_handler(:erb).call(template)
%{
context = CompassRails.context.new(::Rails.application.assets, '', Pathname.new(''))
resolver = ::Sass::Rails::Resolver.new(context)
compiler = Compass::Compiler.new *Compass.configuration.to_compiler_arguments
options = compiler.options.merge({
:syntax => :scss,
:custom => {:resolver => resolver}
})
Sass::Engine.new((begin;#{erb};end), options).render
}
end

Rails 3 - How to use stylesheet's compiled name inside javascript file?

I have javascript file in rails app, where i pull in the stylesheet like this -
loadAssets: function(){
var stylesheet = document.createElement('link');
stylesheet.href = "<%= asset_path('lib/myStyles.css') %>";
stylesheet.rel = 'stylesheet';
stylesheet.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(stylesheet);
}
But asset_path helper used here, just gives plain myStyles.css name, where it should have been compiled name of that css file.
Because of this, i can't expire cache and get new myStyles.css file.
So, my question is, how can i get compiled name of this myStles.css file in my javascript file. Above code containing javascript file also gets compiled.
<%= asset_path('lib/myStyles.css'), :digest => true) %>

Resources