Elm on cloudflare pages
Yeah, Cloudflare pages is out of public beta.
To celebrate, let's deploy some Elm code on there using Yarn.
Make sure you have yarn
ready and start a new project:
mkdir elmo
cd elmo
yarn init
Now you should have a folder named elmo
with a package.json
in there. This is an empty Yarn project, so now we start adding everything we need of elm and elm packaging. Next to the package.json
in the elmo
directory, run:
yarn add parcel-bundler elm node-elm-compiler elm-hot
We now have the tools to start building, let's create the source. Make a directory called src
and add a file called index.html
with:
<!doctype html>
<html lang="en">
<head>
<title>Elmo</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<div id="main"></div>
<script src="./index.js"></script>
</body>
</html>
And a second file called src/index.js
which contains:
import { Elm } from './Main.elm'
Elm.Main.init({
node: document.getElementById('main')
})
This file will make sure Elm knowns where to find our html element to bind to. And now for the last part, src/Main.elm
which contains:
module Main exposing (main)
import Html exposing (Html, text)
main : Html msg
main =
text "Hello, world!"
The above elm code will simply show Hello world. To be able build this, we configure parcel to dig into the source and figure it out. Just before the end of package.json
add a scripts
attribute with two commands parcel commands. The resulting package.json
should be:
{
"name": "elmo",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"elm": "^0.19.1-5",
"elm-hot": "^1.1.6",
"node-elm-compiler": "^5.0.6",
"parcel-bundler": "^1.12.5"
},
"scripts": {
"dev": "parcel src/index.html",
"build": "parcel build src/index.html"
}
}
Tip: if you are adding the "scripts" attribute, make sure you add a comma just before it to make the whole a valid json object.
This will now allow us to issue yarn dev
to start an auto-reloading development server, or yarn build
to build the production release source in the dist
folder.
Configuring Cloudflare pages
Now we have a project up and running, we have to instruct cloudflare pages on how to build the elm project from a git repository and deploy it.
I will forgo the commands to set up a git repository and point Cloudflare pages to it. But the configuration details might still be interesting:
- The build command is
yarn build
. - The build output directory should be set to
/dist
- The root directory should be set to
/
.
Congratulations you have your first Elm website live.
Happy hacking!