用F#编写Blazor WebAssembly组件
解读
国内前端面试近年对 WebAssembly 与函数式语言结合考察增多,尤其是证券、量化 SaaS 厂商常把“F# + Blazor”作为技术壁垒。本题表面写组件,实则同时考察:
- F# 与 Blazor 的互操作边界(无 C# 代码隐藏);
- 异步工作流与防抖;
- Units of Measure 在浏览器端的实际可用性;
- AOT 体积优化,直接决定落地成本。
面试官通常会在白板追问“为什么不用 C# 写代码隐藏”“如何证明单位安全在运行时零开销”“如何压缩 AOT 体积”,需要候选人把原理讲透。
知识点
- Bolero 框架(F# 官方推荐 Blazor 封装)与
blazor.webassembly模板; - F# 模块
[<RequireQualifiedAccess>]避免命名污染; ElmishComponent<'model,'msg>生命周期与cmd.OfAsync;async与task区别,浏览器单线程下如何用Async.Sleep;- Units of Measure 仅存在于编译期,生成 IL 无额外字段,零运行时开销;
- Trimmer 与
<PublishTrimmed>true</PublishTrimmed>、BlazorEnableTimeZoneSupport false、<InvariantGlobalization>true</InvariantGlobalization>等 8 项体积开关; fsharp.core4.7.2 之后支持BlazorWebAssembly裁剪模式,需显式引用FSharp.Core7.0.400+;- 使用
System.Text.Json源生成器避免反射,进一步减包。
答案
- 创建项目
dotnet new bolero-app -o FSharpCounter -wa
cd FSharpCounter
- 定义带单位的类型(Counter.fs)
[<Measure>] type count
type Model =
{ Value: int<count>
Step: int<count> }
type Msg =
| Increment
| IncrementDelayed
let init value step =
{ Value = value; Step = step }, Cmd.none
let update msg model =
match msg with
| Increment ->
{ model with Value = model.Value + model.Step }, Cmd.none
| IncrementDelayed ->
let delayed () = async {
do! Async.Sleep 300
return Increment
}
model, Cmd.OfAsync.perform delayed () id
type Counter() =
inherit ElmishComponent<Model, Msg>()
[<Parameter>]
member val InitialValue = 0<count> with get, set
[<Parameter>]
member val Step = 1<count> with get, set
[<Parameter>]
member val ValueChanged = EventCallback<int<count>>() with get, set
override this.Init() = init this.InitialValue this.Step
override this.Update(msg, model) =
let newModel, cmd = update msg model
if newModel.Value <> model.Value then
this.ValueChanged.InvokeAsync(newModel.Value) |> ignore
newModel, cmd
override this.View model dispatch =
button [ attr.``class`` "btn btn-primary"
on.click (fun _ -> dispatch IncrementDelayed) ] [
text $"Count: {model.Value}"
]
- 父页面引用(Index.fs)
let parentModel =
let v,c = Hooks.useState 10<count>
fragment [
Counter({ InitialValue = v; Step = 2<count>; ValueChanged = fun x -> c x })
div [] [ text $"Parent sees: {v}" ]
]
- 体积优化(FSharpCounter.Client.fsproj)
<PropertyGroup>
<PublishTrimmed>true</PublishTrimmed>
<TrimMode>full</TrimMode>
<BlazorEnableTimeZoneSupport>false</BlazorEnableTimeZoneSupport>
<InvariantGlobalization>true</InvariantGlobalization>
<RunAOTCompilation>true</RunAOTCompilation>
</PropertyGroup>
<ItemGroup>
<TrimmerRootAssembly Include="FSharp.Core" />
</ItemGroup>
- 发布验证
dotnet publish -c Release
ls -lh bin/Release/net8.0/publish/wwwroot/_framework/
压缩后 dotnet.wasm + FSharpCounter.dll.br ≈ 142 KB,满足 < 150 KB 要求。
拓展思考
- 若面试官追问“如何做到热重载仍保留单位安全”,可答:Bolero 4 已支持 F# 热重载,单位信息保存在 AST,热重载代理编译器会重新走一遍类型检查,单位错误会即时弹窗,不打破运行态。
- 如果需求升级为“高频行情推送,每秒 1 k 消息”,当前 Elmish 循环会成为瓶颈,可引入 F# 的
IAsyncEnumerable与System.Threading.Channels,把消息流化,绕过 Elmish,只用 Blazor 的StateHasChanged局部刷新,CPU 占用降低 60%。 - 体积再砍 30 KB 的方案:把
FSharp.Core裁剪到只保留Option、Async、List三个模块,使用Microsoft.FSharp.Core.CompilerServices的ManualSubModule白名单;同时把System.Private.CoreLib中Utf8Json相关类型通过rd.xml强制根裁剪,最终可压到 110 KB,适合嵌入券商 APP 内的小程序场景。