简体   繁体   中英

Import maps + Stimulus: error in JS "Unknown Content-Type text/html"

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM