Files

67 lines
2.6 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Text.Json;
namespace WebApplication1;
public class ViteHelper(IOptions<JsonOptions> options)
{
readonly JsonSerializerOptions jsonOptions = options.Value.JsonSerializerOptions;
public Task<string> RenderAsync(string pathBase, string template, string entryScript, Dictionary<string, string> stringTokens = null)
{
return RenderInternalAsync(pathBase, template, entryScript, null, stringTokens);
}
public Task<string> RenderAsync<T>(string pathBase, string template, string entryScript, T serverData = default, Dictionary<string, string> stringTokens = null)
{
return RenderInternalAsync(pathBase, template, entryScript, serverData, stringTokens);
}
async Task<string> RenderInternalAsync(string pathBase, string template, string entryScript, object serverData = null, Dictionary<string, string> stringTokens = null)
{
var templateFolder = Path.Combine(AppContext.BaseDirectory, "Templates");
var path = Path.Combine(templateFolder, template);
var html = await File.ReadAllTextAsync(path);
if (stringTokens is not null)
{
foreach (var token in stringTokens)
{
html = html.Replace($"<!-- @{token.Key} -->", token.Value);
}
}
html = html.Replace("<!-- @ServerData -->", serverData is not null ?
$"<script>window.__SERVER_DATA__={JsonSerializer.Serialize(serverData, jsonOptions)};</script>" :
"");
#if DEBUG
var viteAssets = $"""
<script type="module" src="http://localhost:5173/@vite/client"></script>
<script type="module" src="http://localhost:5173/{entryScript}"></script>
""";
#else
var manifestPath = Path.Combine(templateFolder, "manifest.json");
var manifestJson = await File.ReadAllTextAsync(manifestPath);
using var manifest = JsonDocument.Parse(manifestJson);
var entry = manifest.RootElement.GetProperty(entryScript);
var jsFile = entry.GetProperty("file").GetString();
var viteAssets = $"<base href=\"{pathBase}/\"/>" +
$"<script type=\"module\" src=\"dist/{jsFile}\"></script>";
if (entry.TryGetProperty("css", out var cssArray))
{
foreach (var css in cssArray.EnumerateArray())
{
viteAssets += $"\n<link rel=\"stylesheet\" href=\"dist/{css.GetString()}\"/>";
}
}
#endif
return html.Replace("<!-- @ViteAssets -->", viteAssets);
}
}