Blazor使用Brotli、PublishTrimmed减少应用大小
文章写作时项目基于.net8,参考链接:
https://learn.microsoft.com/zh-cn/aspnet/core/blazor/components/templated-components?view=aspnetcore-8.0
https://learn.microsoft.com/zh-cn/dotnet/core/deploying/trimming/trimming-options#trim-framework-library-features
启用Brotli压缩降低请求文件大小
下载decode.min.js放到wwwroot文件夹下
在 wwwroot/index.html 文件中,在 Blazor的<script>标记上将autostart设置为false:
1
<script src="_framework/blazor.webassembly.js" autostart="false"></script>
在 Blazor的 <script> 标记之后和 </body> 结束标记之前,添加以下 JavaScript 代码 <script> 块。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22<script type="module">
import { BrotliDecode } from './decode.min.js';
Blazor.start({
loadBootResource: function (type, name, defaultUri, integrity) {
if (type !== 'dotnetjs' && location.hostname !== 'localhost' && type !== 'configuration') {
return (async function () {
const response = await fetch(defaultUri + '.br', { cache: 'no-cache' });
if (!response.ok) {
throw new Error(response.statusText);
}
const originalResponseBuffer = await response.arrayBuffer();
const originalResponseArray = new Int8Array(originalResponseBuffer);
const decompressedResponseArray = BrotliDecode(originalResponseArray);
const contentType = type ===
'dotnetwasm' ? 'application/wasm' : 'application/octet-stream';
return new Response(decompressedResponseArray,
{ headers: { 'content-type': contentType } });
})();
}
}
});
</script>
使用PublishTrimmed裁剪掉不需要的功能
修改.csproj文件,增加如下内容
1 | <PropertyGroup> |
说明:
| 设定 | 说明 |
|---|---|
| PublishTrimmed:true | 启用裁剪。 |
| InvariantGlobalization:true | 删除特定于全球化的代码和数据。 |
| EventSourceSupport:false | 删除与 EventSource 相关的代码和逻辑。 |
| HttpActivityPropagationSupport:false | 删除与诊断支持 System.Net.Http相关的代码。 |
| EnableUnsafeBinaryFormatterSerialization:false | 删除 BinaryFormatter 序列化支持。 |
| MetadataUpdaterSupport:false | 删除与热重载相关的元数据更新特定逻辑。 |
| UseNativeHttpHandler:true | 使用 Android 和 iOS 的默认平台实现HttpMessageHandler并删除托管实现。 |
| UseSystemResourceKeys:true | 将去除程序集的 System.* 异常消息。 从 System.* 程序集引发异常时,该消息是简化的资源 ID,而不是完整消息。 |
其它裁剪详见参考链接