Elm

你可以匯入 Elm 檔案,就像匯入任何其他 JavaScript 檔案一樣。

npm 套件 elm 必須事先手動安裝。你還需要一個 elm.json 組態檔(執行 yarn elm init 來開始,並在必要時修改它)。

index.html
<!DOCTYPE html>
<div id="root"></div>
<script type="module" src="index.js"></script>
index.js
import { Elm } from "./Main.elm";

Elm.Main.init({ node: document.getElementById("root") });
Main.elm
module Main exposing (..)

import Browser
import Html exposing (Html, button, div, text)
import Html.Events exposing (onClick)

main =
Browser.sandbox { init = init, update = update, view = view }

type alias Model = Int

init : Model
init =
0

type Msg = Increment | Decrement

update : Msg -> Model -> Model
update msg model =
case msg of
Increment ->
model + 1

Decrement ->
model - 1


view : Model -> Html Msg
view model =
div []
[ button [ onClick Decrement ] [ text "-" ]
, div [] [ text (String.fromInt model) ]
, button [ onClick Increment ] [ text "+" ]
]

將多個檔案編譯成單一 JS 輸出

#

你可以使用 with 查詢參數將多個 Elm 來源編譯成同一個套件。這可以幫助你縮小套件大小,因為執行時期和共用程式碼等項目是共用的。

index.js
import { Elm } from "./Main.elm?with=./MainB.elm&with=./MainC.elm";

Elm.Main.init({ node: document.getElementById("root") });
Elm.MainB.init({ node: document.getElementById("rootB") });
Elm.MainC.init({ node: document.getElementById("rootC") });

這將執行等同於此命令的動作

elm make Main.elm MainB.elm MainC.elm

with 參數可以使用多次,以包含多個額外的 Elm 程式。

注意 2 件事

  1. 路徑基礎:with 參數值中指定的路徑相對於 import 陳述式中第一個檔案的目錄(在本例中為 Main.elm),而不是相對於包含 import 陳述式的 JS 檔案。
  2. 無意重複:多個輸入有效指定相同的 Elm 檔案,但順序不同(或在開頭的 ./ 等方面有所不同),會被視為不同的資產(因此會重複)

若要避免在大量使用 with 參數(即在多個地方輸入某些組合)時發生這些陷阱,建議使用類似 此第三方解析器套件,它允許為常用的 Elm 檔案組合指定一些簡寫。

時光旅行除錯器

#

在非建置生產環境時,Elm 的除錯模式會自動啟用(使用 parcel build 會自動停用)。你可以設定環境變數 PARCEL_ELM_NO_DEBUG=1,即使在開發模式中也能停用它。