Replies: 1 comment
-
This idea was a bit inspired by the Entity Framework "scaffold-dbcontext" command, that reverse engineer the database into strongly typed models. I know that EF has nothing to do with source generatos, but anyways, scaffolding JS access classes in C# (using either SG or scaffold commands) would be awesome. I don't know exactly how much Blazor users would like something like this, but to me this is game changing. For example, I frequently use libraries like Chart.js, Material, Bootstrap, Sweet Alert, and so on. My JavaScriptWrapper class is huge even in small projects, full of pure boilerplate code. We can compare this, again, with EF: JS interop feels like I'm doing |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
Explore the use of Source Generators to seamlessly interop with Javascript.
Motivation
I believe it is pretty common (it you are frequently calling JS) to have a "JavascriptWrapper" class in a Blazor project that acts like a middle-ground between C# code and Javascript code. What if we could skip this step? From what I've seen about Source Generators in C# 9, it seems to be possible.
Examples
I want to be able to select all the text on an input.
Let's create the usual JavaScript Wrapper class to facilitate our access to Javascript:
Also, we need to add this:
Then, in the Blazor page, we can call:
Of course, we could use the IJsRuntime directly, calling
InvokeVoidAsync
all the time. This is fine for only one function, but if you are interacting with a library in Javascript, it is just cleaner to "hide" it await in a Wrapper class.But what if we could use Generators to create the Wrappers, and call Javascript directly using a dynamic field called
Window
(inspired in the classic ViewBag)?A Generator could explore the code at compile time, convert the function names into camel case (by default), and connect with the corresponding javascript.
Better yet: following the example from Luca's Blog post on Generators (CSV Generator), it may be possible to generate strong typed code to interop with JS.
His example uses Source Generators to parse a .csv file at compile time and create a strong typed way to access it. It is the same thing to scan .js files, and create all the functions in pascal case in the C# side. The developer could select which JS files to parse.
I know that there is a lot of edge cases in parsing JS as text files, but either way, I believe we should explore this at least.
Beta Was this translation helpful? Give feedback.
All reactions