Search code examples
elmelm-port

Using ports with elm-app


I'm trying to use ports with elm-app. Previously I used elm-live and a vanilla setup, and was able to insert ports like this:

index.html

<body>
    <noscript>
        You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
    <script>
      window.addEventListener("load", function(event) {

        var app = Elm.Main.fullscreen(localStorage.session || null);

        app.ports.storeSession.subscribe(function(session) {
          localStorage.session = session;
        });
        ...

This worked, and elm-live seemed to embed elm.js in the <head> of index.html.

When I try to use this setup for ports with create-elm-app, however, the compiled javascript is embedded at the bottom of the <body>, so adding the <script> as I did results in this:

(index):68 Uncaught ReferenceError: Elm is not defined
    at (index):68

What is the best way to embed the JS ports?


Solution

  • The halfzebra/create-elm-app project sets things up a little differently. You'll have to modify the src/index.js file like the example shows in the documentation on Javascript Interop

    import './main.css';
    import { Main } from './Main.elm';
    import registerServiceWorker from './registerServiceWorker';
    
    var app = Main.embed(document.getElementById('root'));
    
    registerServiceWorker();
    
    // ports related code
    app.ports.windowTitle.subscribe(function(newTitle){
        window.document.title = newTitle;
    });