Home > Software engineering >  Is it possible to use .js.erb file in Rails 6?
Is it possible to use .js.erb file in Rails 6?

Time:10-13

I have the following in app/javascripts/custom/test.js.erb

export function test(){
  alert('<%= 5 %>');
}

But the ERB is not interpreted.

Is it possible to use js.erb like this in Rails 6?

CodePudding user response:

It's possible, but you need to make sure that your file is included in the assets pipeline and that it's loaded in your view.

I tested the following example on Rails 6.1:

# in config/initializers/assets.rb
Rails.application.config.assets.precompile  = %w[application.js]

# in app/views/layouts/application.html.erb
<%= javascript_include_tag 'application' %>

# in app/assets/javascripts/application.js
//= require_tree .

# in app/assets/javascripts/test.js.erb
alert('<%= 5 %>');

CodePudding user response:

You can also use js.erb in webpacker, you would need to install a new package rails-erb-loader and also need to configure the webpack loaders.

But no need to worry, webpacker provides built-in rake command to install required packages and configure webpack loaders.

Use:

bundle exec rails webpacker:install:erb

Now just import app/javascripts/custom/test.js.erb to app/javascript/packs/application.js (packs entry point file). And you are all set!

// app/javascript/packs/application.js

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

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

import '../custom/test.js.erb';

Reference docs: https://github.com/rails/webpacker/blob/v5.4.3/docs/integrations.md#erb

  • Related