MicahBrown
MicahBrown

Reputation: 86

Accessing webpacker js in .js.erb views

I'm currently trying to switch from the asset pipeline to webpacker and I'm trying to figure out how to access the packaged javascript from .js.erb views.

All my forms look like this:

<% form_for ..., remote: true do %>

And my controllers all respond like this:

def create
  respond_to do |format|
    format.js
  end
end

But inside the .js.erb templates (create.js.erb for the above example), I don't have access to anything from app/javascript/packs/application.js like I did when I was using the asset pipeline.

If my create.js.erb looks like this:

$('form').prepend("<%=j form_errors(object) %>")

I get an Uncaught ReferenceError: $ is not defined error, because it can't access jQuery.

Here's my webpack environment file:

# config/webpack/environment.js

const { environment } = require('@rails/webpacker')
const coffee = require('./loaders/coffee')

const webpack = require('webpack');
environment.plugins.append('Provide', new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery',
}));

environment.loaders.prepend('coffee', coffee)
module.exports = environment

Any ideas how to access webpacked js in the .js.erb templates.

Upvotes: 0

Views: 219

Answers (1)

code_aks
code_aks

Reputation: 2074

Add these lines in application.js and then try :-

// application.js

require("@rails/ujs").start()
require("turbolinks").start()

require("@rails/activestorage").start()
require("channels")
require("jquery")

window.jQuery = $;           // Add this line
window.$ = $;                // Add this line

Upvotes: 2

Related Questions