2.9

elm make

elm make is a tool for building Elm projects. It takes .elm files and compiles them to JavaScript. In the Building a Simple Page with Elm section, we used elm make to compile HomePage.elm to elm.js like this:

$ elm make src/HomePage.elm --output elm.js

We then imported the elm.js file from index.html.

<!DOCTYPE html>
<html>
  <head>
    ...
  </head>

  <body>
    .
    .
    <script src="elm.js"></script>
    .
    .
  </body>
</html>

We have to go through this process of creating a separate index.html file if we want to add any JavaScript code of our own or import a CSS file or use a Web Component in our app. But if we don’t want any of that, we can simply remove the --output flag. elm make will then automatically create an index.html file for us and put the compiled code in it. We don’t have to manually create that file like we did before. Go ahead and delete the beginning-elm/index.html file and run the following command from the beginning-elm directory in terminal.

$ elm make src/HomePage.elm

Look inside index.html and you’ll see the code that used to be in elm.js. If you open index.html in a browser, you should see the home page for Dunder Mifflin with no CSS styling.

Although elm make allows us to lump everything in one file, it’s best practice to keep the compiled JavaScript code in a separate file. That way, if we need to add more JavaScript code or import any other file later we won’t have to move things around much. It will also improve the testability, code organization, and reusability in our app. We’ll be following this best practice throughout the book, so let’s restore the contents of index.html to what it used to be.

<!DOCTYPE html>
<html>
  <head>
    <link 
      rel="stylesheet" 
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <style>
      .jumbotron {
        background-color: #e6ffe6;
        text-align: center;
      }
    </style>
  </head>

  <body>
    <div id="elm-app-is-loaded-here"></div>
    
    <script src="elm.js"></script>
    <script>
      var app = Elm.HomePage.init({
        node: document.getElementById("elm-app-is-loaded-here")
      });      
    </script>
  </body>
</html>
Back to top
Close