简体   繁体   中英

Hello World in Elm with console / Node

Is there an easy, supported way in Elm of writing console applications, ideally in Node? If so, what does the "Hello, World" look like?

I am aware that there are some packages, most of them not apparently maintained, that purport to do something like this, but they all seem like kludges to some degree.

Elm is a frontend-only language as of 0.18. It might be backend-friendly in the future. But is it not right now. See here

However, that doesn't meant that you can't use it with Node. You just need to use the "worker" mode and send all your data in and out through ports. For example:

port module Main exposing (..)

import Platform

port getName : (String -> msg) -> Sub msg
port sendGreeting : String -> Cmd msg

type alias Model = {}

type Msg =
  GreetUser String

update msg model = 
  case msg of
    GreetUser name -> (model, sendGreeting name)

main = Platform.program 
  { init = ( {}, Cmd.none)
  , update = update
  , subscriptions = \model -> getName GreetUser
}

You can then compile it via elm-make Main.elm --output elm.js and require it in JS like so:

const Elm = require("./elm.js");
const app = Elm.Main.worker();

app.ports.sendGreeting.subscribe((greeting) => console.log(greeting));

app.ports.getName.send("Noah")

There are many apps that do this, such as:

  • elm-sketch-importer
  • elm-verify-examples
  • elm-analyse
  • elm-fuse

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM