Home > OS >  Import maps Stimulus: error in JS "Unknown Content-Type text/html"
Import maps Stimulus: error in JS "Unknown Content-Type text/html"

Time:10-19

I'm having a JS issue with my first Rails app, which I suspect is related to my using import maps instead of Webpack. I've searched and searched but haven't found any discussions of this.

It's a Rails 6 app with some JS via Stimulus, which I installed by adding importmap-rails and then stimulus-rails. It works fine locally, but in production on Heroku the JS doesn't work and I see errors like this in the browser console: Uncaught (in promise) Error: Unknown Content-Type "text/html; charset=utf-8" doFetch https://plainreading.herokuapp.com/assets/es-module-shims-424762490b07cc7f9a37745e8b53356bca11997a8e313f47d780e29009df7e8e.js:580

I'm wondering if it's because I removed Webpack from my app, using How to completely remove webpack and all its dependencies from Rails App. I removed it because I was getting Webpack-related build errors in Heroku, and it's my understanding that I don't need Webpack if I'm using import maps.

A while ago I fixed a similar issue in a static site on Netlify by including this in its netlify.toml config:

[[headers]]
  for = "/*.js"
  [headers.values]
    Content-Type = "text/javascript; charset=utf-8"

I couldn't find any similar config for Heroku. So then I tried customizing the response headers in the app, but I couldn't find a way to do that for my JS files, only for the main HTML response and for public assets.

Here's the repo in case it helps: https://github.com/fpsvogel/plainreading

CodePudding user response:

In the end I solved the issue by doing the following:

  1. Install Rails 7 alpha.
  2. Create a test project with import maps: rails _7.0.0.alpha2_ new importmap-test. (You can use -j to set a different JS bundling option, such as -j esbuild, but the default is import maps.)
  3. Upgrade my main project to Rails 7 alpha.
  4. In my main project, make all JS-related code identical to the corresponding code in the test project. For me this meant overwriting app/javascript/controllers/index.js.

Then my JS worked without errors.

  • Related