Make Shakapacker ES6 functions available in inline Rails views

25 views Asked by At

Rails version: 6.1.3

I am upgrading from Webpacker 5.2 to Shakapacker 7.2.2, and my ES6 functions defined globally on the window object are not available in inline script tags on an ERB view. My project uses both Sprockets and Webpacker/Shakapacker. Here's an example:

In app/javascript/lib/device_detect.ts:

import { isMobile } from "react-device-detect";

export function isMobileBrowser() {
  return isMobile;
}

In app/javascript/packs/application.ts:

import { isMobileBrowser } from '../lib/device_detect';

(window as any).isMobileBrowser = isMobileBrowser;

In app/views/users/dashboard.html.erb:

<div class="dashboard">
  ...

</div>

<script>
  if (isMobileBrowser()) {
    ...
  }
</script>

With my previous Webpacker setup on both development and production, this works just fine. But with Shakapacker, I receive this error in the browser console:

Uncaught ReferenceError: isMobileBrowser is not defined

One of my theories is that Webpacker was not chunking any of my assets and so it was all compiled into one file before being delivered, so I disabled asset chunking. However, that didn't work.

My app has a lot of inline scripts, so I'd prefer not to rewrite/convert them all in some way. I am hoping I can make everything work just as before with Shakapacker instead.

I've tried a lot of things, and nothing has worked. I'd appreciate any help!

0

There are 0 answers