Masa Blazor Pro项目快速入门

Masa Blazor Pro 简介

是一个开箱即用的 Blazor 前端模板框架, 非常适合于做后台管理类项目, 模板设计得非常精良.
github 主页

快速入门

  1. 安装模板
dotnet new --install Masa.Template 
  1. 创建wasm项目
dotnet new masabp --mode Wasm -o Project1
  1. 运行项目
cd Project1
dotnet run
  1. 替换项目中的 decode.mini.js 文件
    新项目中的 decode.mini.js 文件用于在生产环境下使用 brotli 压缩以提高页面加载速度, 但Masa blazor template模板提供的 decode.mini.js 内容是不对的, 需要替换成 google 官方源码, 地址 https://github.com/google/brotli/blob/master/js/decode.min.js
  2. 删除 index.html 对于decode.mini.js 的直接引用, 移到 Blazor.start()调用的上一行.
<script type="module">
  import { BrotliDecode } from './decode.min.js'; // import 方式引入 decode js
  Blazor.start({
    loadBootResource: function (type, name, defaultUri, integrity) {
      if (type !== 'dotnetjs' && location.hostname !== 'localhost') {
        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>

  1. 开发模式下: blazor.webassembly.js 需要设定为 autostart 为 true
    Masa blazor template的项目已经按照微软官方说明, 对于非localhsot的网页请求自动启用的 brotli 压缩机制. 我们知道网页如要使用压缩机制, 浏览器端和服务器端都需要支持. 但对于开发环境, 比如使用VS或VS code, 服务器的blazor dev server是不支持压缩, 所以对于非localhsot的访问, 默认情况下是无法加载页面的, 可以临时关闭压缩加载模式.
<script src="_framework/blazor.webassembly.js" autostart="false" ></script>
<!--临时关闭压缩加载模式: 设定 autostart 为 true-->
<script src="_framework/blazor.webassembly.js" autostart="true" ></script>
  1. 将 index.razor 的url 跳转forceLoad参数调整为false
    曾经遇到index.html无法直接跳转的dashboard视图, 将forceLoad参数设置为false后解决了.
    protected override void OnAfterRender(bool firstRender)
    {
        if(firstRender)
        {
            //Nav.NavigateTo(GlobalVariables.DefaultRoute,true);    
            Nav.NavigateTo(GlobalVariables.DefaultRoute,false);    
        }
    }
  1. 开发期间: 项目发布临时禁用压缩和AOT编译
    压缩和AOT编译的耗时往往会很长, 所以在开发期间可以在项目project中关闭这些编译选项.
<PropertyGroup>
  <RunAOTCompilation>false</RunAOTCompilation>
  <BlazorEnableCompression>false</BlazorEnableCompression> 
  <BlazorEnableTimeZoneSupport>false</BlazorEnableTimeZoneSupport>
  <BlazorWebAssemblyPreserveCollationData>false</BlazorWebAssemblyPreserveCollationData>   
</PropertyGroup>
  1. 参考资料
posted @ 2023-03-15 07:35  harrychinese  阅读(331)  评论(0编辑  收藏  举报