一般来说在.net core使用WebAssembly
都是Blazor
,但是Blazor
渲染界面,.net core也提供单纯的WebAssembly
这篇博客我将讲解如何使用单纯的WebAssembly
安装WebAssembly
模板
dotnet new install Microsoft.NET.Runtime.WebAssembly.Templates
安装完成以后在vs的新建项目的时候会出现如图的模板
然后我们下一步创建一个WebAssembly
的项目,WebAssembly
的项目很单纯,项目结构如下图:
我们可以看到项目及其简单,分别查看文件代码
Program.cs
using System;
using System.Runtime.InteropServices.JavaScript;
Console.WriteLine("Hello, Browser!");
public partial class MyClass
{
[JSExport]
internal static string Greeting()
{
var text = $"Hello, World! Greetings from {GetHRef()}";
Console.WriteLine(text);
return text;
}
[JSImport("window.location.href", "main.js")]
internal static partial string GetHRef();
}
main.js
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
import { dotnet } from './dotnet.js'
const { setModuleImports, getAssemblyExports, getConfig } = await dotnet
.withDiagnosticTracing(false)
.withApplicationArgumentsFromQuery()
.create();
setModuleImports('main.js', {
window: {
location: {
href: () => globalThis.window.location.href
}
}
});
const config = getConfig();
const exports = await getAssemblyExports(config.mainAssemblyName);
const text = exports.MyClass.Greeting();
console.log(text);
document.getElementById('out').innerHTML = text;
await dotnet.run();
index.html
<!DOCTYPE html>
<!-- Licensed to the .NET Foundation under one or more agreements. -->
<!-- The .NET Foundation licenses this file to you under the MIT license. -->
<html>
<head>
<title>WebAssemblyDemo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="modulepreload" href="./main.js" />
<link rel="modulepreload" href="./dotnet.js" />
</head>
<body>
<span id="out"></span>
<script type='module' src="./main.js"></script>
</body>
</html>
这些代码及其简单,如果在遇到js性能瓶颈的时候就可以使用当前这种模式,使用单纯的WebAssembly
去提高我们的产品性能
试试看执行一下程序,效果如下图:
标签:WebAssembly,const,text,js,如何,单纯,dotnet From: https://www.cnblogs.com/hejiale010426/p/17084259.html