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
以在开发模式下禁用它。