Search code examples
ruby-on-railsruby-on-rails-7

The asset xxx is not present in the asset pipeline - Rails 7


I am struggling with a problem. I migrated my app from rails 6 + webpacker to rails 7 + jsbundling + webpack following this tutorial : https://github.com/rails/jsbundling-rails/blob/main/docs/switch_from_webpacker.md

However, I get this error "The asset 'transportation_calculator.js' is not present in the asset pipeline" everytime I access a page.

Here is my manifest.json :

//= link_tree ../../javascript .js
//= link_directory ../stylesheets .scss

//= link_tree ../images
//= link_tree ../builds

In my application.html.erb I have :

<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track": "reload" %>
<%= javascript_include_tag "application", "data-turbolinks-track": "reload", defer: true %>

And I start the haml page that I'm trying to load with:

= javascript_include_tag 'transportation_calculator.js'

Thank you very much for you help !

I tried to change the path in webpack.config.js to :

  entry: {
    // add your css or sass entries
    application: [
      './app/javascript/application.js',
      './app/assets/stylesheets/application.scss',
    ],
  }

without success. The error remained the same.


Solution

  • <%= javascript_include_tag 'transportation_calculator.js' %>
    

    When you do this in your template rails and sprockets will try to find that file in the asset path. Because you're using jsbundling-rails "app/javascript" is not one of these paths:

    >> Rails.application.config.assets.paths
    => 
    ["/home/alex/code/stackoverflow/app/assets/builds",
     "/home/alex/code/stackoverflow/app/assets/config",
     "/home/alex/code/stackoverflow/app/assets/images",
     "/home/alex/code/stackoverflow/app/assets/stylesheets",
    ...
    

    When you run bin/dev webpack will compile app/javascript/application.js and save it into app/assets/builds/application.js this is the file that's being loaded with:

    <%= javascript_include_tag "application" %>
    

    What you need to do is to import your file in application.js:

    // app/javascript/application.js
    
    import "./transportation_calculator"
    

    If you actually, don't want webpack to compile anything, you can add app/assets/javascripts directory that will be loaded only with sprockets:

    app/
    └── assets/
        └── javascripts/
            └── transportation_calculator.js
    

    Make sure to precompile it:

    // app/assets/config/manifest.js
    
    //...
    //= link_tree ../javascripts .js
    

    Now you can load that file directly with
    javascript_include_tag "transportation_calculator"