Remotely load JS via Webpacker

124 Views Asked by At

I'm running into an issue on loading a very basic JS script remotely from my Rails/Webpacker app.

This is my JS script:

# app/javascript/some.js
console.log('loaded');

First, I'm including my pack into my Rails view and the "loaded" string is rendered in the console of the browser. Everything good so far.

Next, I want to be able to have this script loaded remotely. So I create an HTML file like this:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title></title>

  <script type="text/javascript" src="http://localhost:3000/packs/js/some.js"></script>

</head>
<body>

</body>
</html>

Absolutely nothing happens!

I know for sure it loads well because if make e.g. a typo in the src I get a 404 in the console: 'Failed to load resource: the server responded with a status of 404 (Not Found)'

Now, when I check my manifest, I see that three assets are loaded:

# manifest.json

    "some": {
      "assets": {
        "js": [
          "/packs/js/runtime.js",
          "/packs/js/vendors-node_modules_webpack-dev-server_client_index_js_protocol_ws_3A_hostname_localhost_por-95065b.js",
          "/packs/js/some.js"
        ]
      }
    }

So, when I include these JS script is my HTML, it works:

# working example

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title></title>

  <script type="text/javascript" src="http://localhost:3000/packs/js/runtime.js"></script>
  <script type="text/javascript" src="http://localhost:3000/packs/js/vendors-node_modules_webpack-dev-server_client_index_js_protocol_ws_3A_hostname_localhost_por-95065b.js"></script>
  <script type="text/javascript" src="http://localhost:3000/packs/js/some.js"></script>

</head>
<body>

</body>
</html>

But the thing is: I don't want to include three times a JS in my HTML (for several reasons).

So, my question is: what can I do to make my 'app/javascript/some.js' file load remotely where I only need to include just one JS file.

0

There are 0 best solutions below