使用elm-app端口

时间:2018-03-24 00:25:49

标签: elm elm-port

我正在尝试使用elm-app的端口。以前我使用elm-live和vanilla设置,并能够插入这样的端口:

的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;
        });
        ...

这很有效,而elm-live似乎将elm.js嵌入到index.html的<head>中。

但是,当我尝试将此设置用于create-elm-app的端口时,已编译的javascript嵌入在<body>的底部,因此我添加<script>会导致这样:

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

嵌入JS端口的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

halfzebra/create-elm-app项目的设置略有不同。您必须像example shows in the documentation on Javascript Interop

一样修改src/index.js文件
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;
});