Elm
他のJavaScriptファイルと同様に、Elmファイルをインポートできます。
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つの点に注意してください。
- パスベース:
with
パラメータの値で指定されたパスは、import
文の最初のファイル(この場合はMain.elm
)のディレクトリを基準とした相対パスであり、import
文を含むJSファイルを基準とした相対パスではありません。 - 意図しない重複: 実際には同じElmファイルを指定しているが、順序が異なる(または先頭の
./
などが異なるなど)複数のインポートは、異なるアセットとして扱われ(したがって、重複します)。
with
パラメータを多用する場合(つまり、複数の場所でいくつかの組み合わせをインポートする場合)、よくあるElmファイルの組み合わせのショートカットを指定できるこのサードパーティのリゾルバーパッケージを使用することをお勧めします。
タイムトラベルデバッガ
#本番環境向けにビルドしていない場合、Elmのデバッグモードは自動的に有効になります(parcel build
では自動的に無効になります)。開発モードでも無効にするには、環境変数PARCEL_ELM_NO_DEBUG=1
を設定できます。