Embedding Elm App in Page
So far, we’ve been using
elm-reactor to build and run our app. This is a great way to quickly start developing in Elm, but it has its own limitations. The page that hosts our Elm application is generated by
elm-reactor, so we don’t control it. For example, we cannot add our CSS file to style our components.
To get a full control over the application, we need to embed our Elm application into an HTML file.
Creating HTML to Host Elm App
We’ll start by creating a simple HTML page that will host our application. I’ve created
index.html file with the following content:
It’s a simple HTML document with a
div element with the
app id. We will use this
div to embed our application.
Building Elm App with
elm-reactor did this for us under the hood. This time we will use
elm-make for this.
To build the application you need to navigate to the folder with the source code and call
elm-make from the console:
This command tells
elm-make to compile the
Main.elm file and all its dependencies and save the final build into the
main.js file contains required Elm framework pieces, additional packages that we used, and the code of the application. It’s everything we need to run our application.
Note 1: For the first run
elm-make would ask to download packages that are needed for your application. They will be downloaded and saved into the
Note 2: If you’ll run
elm-make Main.elm, without passing the
--output main.js parameter, the result will be an
Embedding Elm App in HTML
All we need to do is to include our compiled file in the HTML file and embed our app. Here’s the code for that:
script tag with our
main.js file, and added script to embed our app into the
If we open
index.html (we can still use
elm-reactor as a local server), we’ll see our app. It looks the same as when running it directly from the
The last step for today would be to add some styles to our app.
Applying CSS to Elm App
Now let’s add some styling to our application. I’ve created the
main.css file that will contain all the styles for the app. Adding it to HTML is straightforward:
And here’s the code for the
view function that applies CSS classes to elements. Note the class attributes passed to