About code organization in eex templates, with socket and Presence

You are doing the “easy and simple” thing but

I am not entirely satisfied with this solution,

because it isn’t optimal for pages that make significant use of JavaScript.

I posted a quick example here of how to convert to a modular style. In your case there is the additional challenge that you will likely need a separate bundle for each page - something that is handled by bundlers with “multiple entry points”, i.e. one bundle per entry point. There is a (Brunch) discussion about that:

However note that Phoenix 1.4 uses Webpack 4 instead of Brunch.

Technically the code that you put inside the script tags is supposed to be at the end of app.js (the page bundle) - in which case you wouldn’t need to attach getPhoenixSocket and getPhoenixPresence to the global window object.

So your challenge is to get Brunch to generate the app1.js, app2.js, etc. bundles that you need for your various pages and include them in the page templates (and remove app.js from the layout template app.html.eex).

2 Likes