Rails 7: It appears that the browser is disregarding all importmap JavaScript packages

Last week I worked through two different tutorials, successfully achieving most of the tasks. However, three crucial issues remain unresolved. Upon closer inspection, it became evident that all three problems revolve around the browser seemingly disregarding javascript packages imported via importmap script tags.

The first tutorial is DHH's Rails 7 Demo. In this demo, he uses the LocalTime package to display how long ago a post was created. The second instance of this issue arises later in the same demo, where he employs the turbo package to introduce a turbo stream for live updates in a view. The final occurrence comes from a Learnetto tutorial, where the author showcases importing React components from the javascript folder.

For brevity, I will focus on sharing my code related to the initial problem: the time-ago method using the LocalTime package. By solving this particular issue, I hope to resolve the remaining two as they appear interconnected. However, if deemed necessary, I am willing to provide the code for the other two challenges upon request.

Versions and gems:

Rails version: 7.0.3.1
Ruby version: 3.0.0p0
Gemfile: gem "importmap-rails" (Included by default in a new rails app)
Gemfile.lock: importmap-rails (1.1.5)
Safari browser: 15.6 (JavaScript enabled with testing also conducted in Chrome)

config/importmap.rb:

pin "application", preload: true
pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true
pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true
pin "@hotwired/stimulus-loading", to: "stimulus-loding.js", preload: true
pin_all_from "app/javascript/controllers", under: "controllers"

pin "trix"
pin "@rails/actiontext", to: "actiontext.js"
pin "local-time", to: "https://ga.jspm.io/npm:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="274b4844464b0a534e4a42671509160917">[email protected]</a>/app/assets/javascripts/local-time.js"

app/javascript/application.js:

import "@hotwired/turbo-rails"
import "controllers"
import "trix"
import "@rails/actiontext"
 
import LocalTime from "local-time"
LocalTime.start()

application.html.erb (Inside head tags):

<%= javascript_importmap_tags %>

Relevant excerpts from Web Inspector in browser in development environment:

<!DOCTYPE html>
<html>
<head>
<script type="importmap" data-turbo-track="reload">
***(All expected imports are listed here, including the crucial one:)***
"local-time": "https://ga.jspm.io/npm:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9a5a6aaa8a5e4bda0a4ac89fbe7f8e7f9">[email protected]</a>/app/assets/javascripts/local-time.js",
</script>
<link rel="modulepreload" href="....">. ***(Four instances of these)***
</head>

app/views/post/post/html.erb:

Posted <%= time_tag post.created_at, "data-local": "time-ago" %>

Expected output in the view: Posted 10 minutes ago

Actual output observed: Posted August 19, 2022 19:57 (The same result appears even when omitting "data-local": "time-ago")

Here are some additional troubleshooting steps attempted:

  • Inserting non-existent packages in both the importmap.rb and application.js files to test for potential errors. (No errors were triggered, and the fake packages did not show up in the script tags within the web inspector).
  • Downloading the packages into the vendor/javascripts folder instead of utilizing the CDN

Additional query: Is there a way to verify if ANY importmap js is functioning in my browser?

Thank you in advance for any guidance provided.

Answer №1

This response focuses on addressing a specific issue rather than discussing importmap:

My expectation for the display: "Posted 10 minutes ago"

In Rails, there is a useful method called DateHelper#time_ago_in_words

To utilize it in your view, you can use the following syntax:

Posted <%= time_ago_in_words(post.created_at) %> ago

Additionally, this method has an alias known as distance_of_time_in_words_to_now

You can also incorporate locales with this method (ensure accurate translations are maintained in the locale files) as it employs distance_of_time_in_words internally

Answer №2

After hours of troubleshooting, I finally caught the typo that was behind this issue.

Upon inspecting my importmap file, I found:

pin "@hotwired/stimulus-loading", to: "stimulus-loding.js", preload: true

instead of

pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true

(It turns out the letter "a" in the word loading was the culprit).

This seemingly minor typo was actually causing all my javascript packages to malfunction. Once corrected, even my turbo_streams started functioning properly again.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to send an array value from JavaScript Ajax to PHP and then successfully retrieve and read it?

As a newcomer to PHP, I am facing a challenge in saving multiple values that increase dynamically. I'm passing an array value using the following method from my JavaScript code. $(".dyimei").each(function(i,value){ if($(this).val()=="") ...

jQuery click() function fires twice when dealing with dynamic elements

I am loading content from a database through ajax into a div and then when clicking on any of these content pieces, it should reload new content. The ajax request is initialized as a method within a class that I call at the beginning: function Request(ta ...

Use jQuery to swap out two div classes within a table cell (TD) if they are

Although I'm making progress, I must confess that jQuery and CSS are not my strong suits. The objective: To create a dynamic div within a table data cell for a calendar feature. The content of the div varies based on the date range input. A filled d ...

How can I make JavaScript skip over a specific portion of my HTML code?

I have a script running on all pages of my website. I would like it to continue running on the specific page, but ignore a certain section. For example: <p>process with javascript</p> <p>skip, instruct javascript function to ignore</ ...

What is the best way to retrieve all the values of a specific field from a store?

Is there a way to retrieve all the values of a specific field from a store without manually selecting each cell? In my grid, I am looking to extract all the values from a particular column directly from the store. Is this achievable without any manual sel ...

What is the name of the JavaScript code editor that includes line numbering for plain text?

Looking to incorporate a text area with line numbering features. I experimented with EditArea, but encountered difficulties when working with text files. While syntax highlighting for various programming languages would be a nice touch, my primary focus ...

Omit specific TagNames from the selection

How can I exclude <BR> elements when using the statement below? var children = document.getElementById('id').getElementsByTagName('*'); Is there a special syntax for getElementsByTagName that allows me to achieve this, or is the ...

Step-by-step guide on placing a geometry shape precisely at the mouse click location using ThreeJS

I'm attempting to create a circle in the exact position where the mouse is clicked, but the circle ends up being drawn slightly off. Can anyone pinpoint what needs to be adjusted in the code below? var camera = new THREE.PerspectiveCamera ...

Assign a value to a dropdownlist in Javascript

I am facing an issue with setting the selected value of a dropdownlist that is populated by a webservice using ajax cascading dropdown. It seems like the values are not available when the javascript code runs, even though I have placed it at the bottom o ...

Best return type for a webservice triggered using jQuery but not requiring any data to be returned

I am currently working on a web service that utilizes several methods. These methods do not have significant impact on the client side as I call them using jQuery/ajax. My main concern is regarding the recommended return type. Typically, I would return JS ...

What is the best way to display "No results found" in Mat-select-autocomplete?

I am working with the mat-select-autocomplete for a multiselect dropdown. When searching for values that are not in the list, I want to display a message saying "No results found". Can someone please help me achieve this? Link to Code ...

the ultimate guide to leveraging a single slot to edit various columns within data tables

Utilizing vuetify, I have successfully created a reusable data table. The headers and items are passed as props to allow for the data table to be used in various components. While employing slots, I have taken a unique approach by implementing a column-ba ...

Using JQuery to Execute Matching Based on Text Within <A> Elements

After reviewing the resources on Jquery Extract URL from Text and jquery match() variable interpolation - complex regexes, I am still a bit confused. The issue at hand is that I have a webpage with a dropdown menu at the top. Inside the dropdown, there ...

Using an HTML file as the source for an image in the <img src=""> tag is a simple process that can greatly enhance the visual appeal of your webpage

My goal is to utilize an html file as the source for an image file within the <img src=""> tag in order to prevent mixed-content warnings when using an http image over https. For instance: index.html: <img src="./image.html" > image.htm ...

Moving the panel to follow the mouse cursor in Firefox Add-on SDK

Is there a way to show a panel on the screen at the exact position of the mouse? I'm finding it difficult to understand how to change the position of the panel in Firefox SDK, as the documentation lacks detailed information. ...

Using AJAX in JavaScript, learn how to send an array of base64 images to Java in a single call

My application allows users to upload multiple images simultaneously. Once uploaded, all image sources are stored in an array and sent using an ajax call. Unfortunately, the ajax call returns an error stating that the size of the data is too long. Below ...

Angular HTTP client implementation with retry logic using alternative access token

Dealing with access tokens and refresh tokens for multiple APIs can be tricky. The challenge arises when an access token expires and needs to be updated without disrupting the functionality of the application. The current solution involves manually updati ...

Adding a Byte to a Hexadecimal Escape Sequence in JavaScript: A Step-by-Step Guide

I am currently facing an issue with JavaScript and due to my limited expertise in this area, I am seeking assistance. The challenge at hand involves hashing a "string" of bytes, where I need to add another byte that is generated within a script. Adding th ...

acquire the document via ng-change

I need help converting this code to be compatible with angular.js so that I can retrieve the data URL and send it using $http.post <input type="file" id="imgfiles" name="imgfiles" accept="image/jpeg" onchange="readURL(this);"> function readURL(i ...

Unexpected outcomes experienced with AJAX in ASP.NET due to javascript integration

I experimented with two methods (server and client side) for initiating a JavaScript AJAX call to post a ticket on a website and then retrieve a link containing the ticket number for tracking or editing purposes. However, both approaches yielded different ...