Elm in the browser

We've finally graduated from the REPL--now it's time to start working with the browser! Open up your favorite text editor and create a new file named ToDoApp.elm in the same directory you installed the Elm HTML package.

Let's try just producing some plain text to start. When we're writing for the browser, Elm will look for a value called main to kick things off. So let's define main with a String value and see what happens.

main = "Hello, world!"

elm-reactor

The elm-reactor tool will let you easily run your Elm code in the browser. In the same directory as your project, run this command:

$ elm-reactor
elm reactor 0.17.1
Listening on http://localhost:8000/

Now go to that address http://localhost:8000. You should see the contents of your project folder listed, including your ToDoApp.elm file. That item is a link--click it and you'll see the result of your efforts so far.

Hello again, Elm compiler!

If you copied that code exactly, you'll run into this error message. Since we're running our code in the browser now, this is where the compiler talks to you instead of the Terminal.

Detected errors in 1 module.
==================================== ERRORS ====================================



-- BAD MAIN TYPE --------------------------------------------------- ToDoApp.elm

The `main` value has an unsupported type.

1| main = "Hello, world!"
   ^^^^
I need Html, Svg, or a Program so I have something to render on screen, but you
gave me:

    String

According to the compiler, we're not allowed to make main a String. It wants one of these types of values: Html, Svg, or Program. So how do we turn our String into one of these valid types?

The Html module

I'll give you a hint. The type of value we want for now is the Html type. With this information, you now know that you need a function to transform your String into an Html value. Finding one is just a matter of searching through the docs for a function with the type signature String -> Html.

It turns out there's just such a function in the Html module. This is the text function. The docs give it this plain English description:

Just put plain text in the DOM. It will escape the string so that it appears exactly as you specify.

This is just what we need! So to get our main displaying our text, we can import that Html module and have main call Html.text. Now, ToDoApp.elm looks like this:

import Html

main = Html.text "Hello, world!"

Refresh your page in the browser and you can now see your text!

See how easy that was? You barely needed my help at all. The combination of the compiler and the docs is enough to get you through most any tough spot.

results matching ""

    No results matching ""