【问题标题】:Using ports with elm-app使用带有 elm-app 的端口
【发布时间】:2018-03-24 00:25:48
【问题描述】:

我正在尝试将端口与 elm-app 一起使用。以前我使用elm-live 和香草设置,并且能够插入这样的端口:

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 的 &lt;head&gt; 中。

但是,当我尝试将此设置用于带有 create-elm-app 的端口时,编译后的 javascript 嵌入在 &lt;body&gt; 的底部,因此像我一样添加 &lt;script&gt; 会导致:

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

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

【问题讨论】:

  • 是halfzebra的图书馆吗?端口是described here
  • 是的,做到了。随意评论,我会标记为正确的。

标签: elm elm-port


【解决方案1】:

halfzebra/create-elm-app 项目的设置略有不同。您必须修改 src/index.js 文件,如 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;
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    相关资源
    最近更新 更多