Javascript EEX templates

If you want interpolated Javascript this can be served up as others have noted, you just make a .js.eex file under templates and have a view render it from a routed path just like .html.eex. But it isn’t part of your assets path because it isn’t, on its own, a javascript asset.

In this case you can open a port and run webpack within elixir. And use a replace plugin to set your variables from process.env in js.

@benwilson512 Thanks, it’s a potential solution, but I’m afraid it can get messy, since I need to require some other files which are part of the assets.

@lud Are you aware of any docs related to your proposition?

The config for your script should be as small as possible and without dependencies. Your static script can then load the endpoint with your dynamic data, and use the data it contains to initialize all the webpack fanciness you have compiled once into a static script/many static scripts.

E.g. your app.js could contain something akin to:

import App from "./main.js";
import ajax from "./ajax.js"

function start(id_of_user) {
  ajax("https://example.com/dynamic/config.json", {params: {id: id_of_user}})
    .then(config => {
      App.start(config)
    });
}

window.start = start

Creating the script like this means nothing besides the top level app.js depends on your dynamic configuration coming from your phoenix app. They just get the dependency injected. This makes testing easier, but also let’s you create a static js file, which is perfectly cacheable, which still reacts to the config it retrieves from your single endpoint, which returns just the few things, which cannot be static and nothing more.

2 Likes

No bout you can look at how phoenix starts webpack in dev mode and do the same.

But @LostKobrakai solution would be the simple one : just render the config only (I told you how to render js in an older comment above).

1 Like