Building Microfrontends Bonus Part - Rewriting an app with Elm

If you haven't heard of it yet, Elm is this super cool Pure Functional programming language for the front-end that compiles to JavaScript.

Check their guide if you want to installed and learn about the language.

We are going to rewrite Cart to use Elm, but this isn't really a tutorial about Elm, there are already a lot of good links for that, instead, I'll jump to the working code already:

As you can see on the code above, on our Elm app we render the products list, and listens for addToCart events coming from the ports. On the JavaScript part on the HTML, we listen to the events on the window and send them to Elm.

Basically you can copy the Elm code above to a Main.elm file. The javascript that bootstraps the app though will not go inline, instead, we will create a bootstrap.js file:

It inits the Elm app, listen to window events and send it to Elm.

Then, create an index.html to load the bundled app:

Where does this dist/bundle.js comes from? Yeah, we need something to build our app. Create a file called, give it executable permissions with chmod +x and add this inside:

mkdir -p dist
elm make Main.elm --output compiled.js
cat compiled.js bootstrap.js > dist/bundle.js
cat index.html | sed -e "s#dist#$PUBLIC_URL#" > dist/index.html

Special attention to the last line, it replaces dist path to the PUBLIC_URL when we need, solving the problem explained on Part III.

Now, to run it on heroku, create this Dockerfile:

Now deploy it to heroku with heroku container:push web and done! It is running, and working, and communicating with other apps, and nobody knows it changed from React to Elm, cause it renders the same and uses the same events to communicate, even heroku isn't much aware that it changed, cause we are inside Docker.

How cool is this? You can check the full source-code here.

If you want to add server-side rendering as well, try elm-static-html.

That was it folks, see ya next time!