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 程序。
注意两件事
- 路径基准:
with
参数值中给出的路径相对于import
语句中第一个文件(在本例中为Main.elm
)的目录,而不是相对于包含import
语句的 JS 文件。 - 无意重复: 多个导入实际上指定了相同的 Elm 文件,但顺序不同(或在领先的
./
等方面有所不同),将被视为不同的资产(因此将被重复)。
为了避免在大量使用 with
参数时出现这些陷阱(即在多个地方导入某些组合),建议使用类似于 这个第三方解析器包,它允许为常用的 Elm 文件组合指定一些简写。
时光倒流调试器
#当不为生产环境构建时,Elm 的调试模式会自动启用(使用 parcel build
会自动禁用)。您可以设置环境变量 PARCEL_ELM_NO_DEBUG=1
以在开发模式下禁用它。