Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a specific javascript file in a specific view in rails and webpack?

Tags:

so I am building an app with rails and webpack, and I got rid of assets pipeline and sprockets. So far, nothing exceptional.

I know that webpack throws all JavaScript files that lives in app/javascript/packs and the browser executes them all regardless of which views is actually loaded and this can causes errors.

What I am trying to do is to make the browser execute a specific JavaScript file for a specific view.

Example: if the view is foo.html.erb, the browser execute the JavaScript foo.js that lives in ~/app/javascript/packs only when foo.html.erb called.

Remember that I am using webpack so putting the helper <%= javascript_include_tag : 'foo'%> will not work in my case since I work with webpack instead of the assets pipeline

Is there a simple and straightforward way of doing this ?

like image 986
cobak Avatar asked Aug 07 '18 04:08

cobak


1 Answers

You can read document here https://github.com/rails/webpacker and using helper:

<%= javascript_pack_tag 'application' %>
<%= stylesheet_pack_tag 'application' %>

Example. You create a foo.js at ~/app/javascript/packs You can call this file at view

<%= javascript_pack_tag 'foo' %>
like image 74
1Rhino Avatar answered Sep 28 '22 18:09

1Rhino