How do I use NPM packages in Blazor WebAssembly?
To use .npm packages in a Blazor WebAssembly application, follow these steps: Create a Blazor WebAssembly application in Visual Studio 2019 using this link. Right-click on the application and create a new folder named npm_packages. Open the npm_packages folder directory via command prompt and run the following command to initialize NPM in the application. npm init -y Once the command is executed, it will create a new package.json file in the npm_packages directory. Continue in the command prompt by executing the following command to install a JavaScript bundler named webpack and its CLI as development dependencies. npm install webpack webpack-cli –save-dev Finally, install the required .npm package. In this demo, we installed Syncfusion Maps by running the following command. npm install @syncfusion/ej2-maps Within the npm_packages folder, create a new folder called src, and then a JavaScript file called index.js. Include the build script for the package.json file, as shown in the following, which uses webpack to bundle the JavaScript file. This script tells webpack to use the index.js file in the src folder as the source file. The output directory of the bundled file is then set to be created under the js folder in the wwwroot folder directory as index.bundle.js. { "name": "npm_packages", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build": "webpack ./src/index.js --output-path ../wwwroot/js --output-filename index.bundle.js --mode=development" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "webpack": "^5.58.1", "webpack-cli": "^4.9.0" }, "dependencies": { "@syncfusion/ej2-maps": "^19.3.44" } } Navigate to the Index.razor page and insert a div tag with the id set as element to display the Syncfusion Maps component. [Index.razor] @page "/" <h1>NPM Packages Demo</h1> <div id="element"></div> In the index.js file, import and declare the Syncfusion Maps component. Finally, the component is appended to the div tag with the id set as element in the Index.razor page. [index.js] import { Maps } from '@syncfusion/ej2-maps'; const map = new Maps({ layers: [ { layerType: "OSM" } ] }); map.appendTo('#element'); Modify the index.html file with the following code to help Blazor inject a script after it starts. Note: This step is primarily for including the Syncfusion Maps component; if you’re using something else, you can skip it. [index.html] <!DOCTYPE html> <html> <head> <title>NPM_Demo</title> <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" /> <link href="css/app.css" rel="stylesheet" /> </head> <body> ……………….. <script src="_framework/blazor.webassembly.js" autostart="false"></script> <script> Blazor.start().then(function () { var customScript = document.createElement('script'); customScript.setAttribute('src', 'js/index.bundle.js'); document.head.appendChild(customScript); }); </script> </body> </html> Add a prebuild step to the *.csproj file that will run the .npm commands whenever you compile or build the application. [.csproj] <Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly"> ……………………….. <Target Name="PreBuild" BeforeTargets="PreBuildEvent"> <Exec Command="npm install" WorkingDirectory="npm_packages" /> <Exec Command="npm run build" WorkingDirectory=" npm_packages " /> </Target> </Project> Run the sample to see the demonstration.
How do you style Blazor components with SCSS?
SCSS, also known as Sassy CSS, is a CSS advancement that includes advanced features. It is more expressive, loads faster, uses fewer lines of code, and encourages proper rule nesting. It has all of the features of CSS and more, making it a good choice for developers to use. It is an SASS-specific file, similar to CSS, but with improved formatting. To style your Blazor components with SCSS, follow these steps: Create a Blazor WebAssembly application by referring to this link. Create a new folder named TowerRange, and inside it, create TowerRange.razor, a new Blazor component, and define it as shown. [TowerRange.razor] <div class="tower"> <div class="tower-range @BackgroundStyle" style="height: @Height" aria-valuenow="@CurrentValue" aria-valuemin="0" aria-valuemax="80"> </div> </div> @code { [Parameter] public int CurrentValue { get; set; } [Parameter] public BackgroundColor Color { get; set; } = BackgroundColor.LightGrey; public enum BackgroundColor { LightGrey, MediumGrey, DarkGrey } private string BackgroundStyle => $"BackColor-{Color.ToString()}"; private string Height => $"{CurrentValue}%"; } Create a new SCSS file named TowerRange.scss inside the TowerRange folder and specify the style required for the TowerRange component as shown in the following. [TowerRange.scss] .tower { width: 15px; height: 200px; background-color: #fff; position: relative; } .tower-range { width: 100%; display: block; font-family: arial; font-size: 12px; background-color: white; color: #fff; position: absolute; bottom: 0; } $BackColor-LightGrey: #d4d3d2; $BackColor-MediumGrey: #8f9194; $BackColor-DarkGrey: #585959; .BackColor { &-LightGrey { background-color: $BackColor-LightGrey; } &-MediumGrey { background-color: $BackColor-MediumGrey; } &-DarkGrey { background-color: $BackColor-DarkGrey; } } Add the following code in the Helper.scss in the Shared folder to provide custom styles for the TowerRange component’s appearance in the Index.razor main page. [Helper.scss] .marginStyle { margin-left: 2px; display: inline-block; } To combine all SCSS files, create an App.scss file in the main application and add the following code. [App.scss] @import 'TowerRange/TowerRange'; @import 'Shared/Helper'; Now, follow this link to install the Web Compiler extension and restart Visual Studio. After restarting, right-click App.css and select Web Compiler > Compile File. The compilerconfig.json file will be generated under the main application. Add the following code to the compilerconfig.json file. [ { "outputFile": "wwwroot/css/site.css", "inputFile": "App.scss", "minify": { "enabled": true }, "options": { "sourceMap": true } } ] Insert the site.css file created by the Web Compiler into the index.html page. <head> ……………………. <link href="css/site.css" rel="stylesheet" /> </head> To run Web Compiler during the build action (F5), install a NuGet package, or right-click compilerconfig.json and select Web Compiler > Enable compile on build, which automatically installs this NuGet package. <Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly"> ……………………. ……………………. <ItemGroup> <Content Remove="compilerconfig.json" /> </ItemGroup> <ItemGroup> <None Include="compilerconfig.json" /> </ItemGroup> <ItemGroup> <PackageReference Include="BuildWebCompiler" Version="1.12.394" /> <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="5.0.10" /> <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="5.0.10" PrivateAssets="all" /> <PackageReference Include="System.Net.Http.Json" Version="5.0.0" /> </ItemGroup> </Project> Add the TowerRange component to the Index.razor page, as shown in the following. @page "/" @using SCSS.TowerRange; <h1> Blazor component styling with SCSS </h1> <div class="marginStyle"> <TowerRange CurrentValue="20" Color="TowerRange.BackgroundColor.DarkGrey" /> </div> <div class="marginStyle "> <TowerRange CurrentValue="40" Color="TowerRange.BackgroundColor.MediumGrey" /> </div> <div class="marginStyle "> <TowerRange CurrentValue="60" Color="TowerRange.BackgroundColor.LightGrey" /> </div> When you run the application, you will see the following output.
How do you enable CORS in a Blazor Server application?
CORS stands for cross-origin resource sharing, and it is an HTTP header-based mechanism that allows the server to tell the browser whether to accept a request from a domain, port, or scheme other than its own. It is based on a process in which the browser sends a “preflight” request to the server, and the server responds with response headers indicating whether the request can proceed or not. The browser will either succeed or fail the request based on what these headers say. The browser sends headers that indicate the HTTP method and headers that will be used in the actual request in the preflight request. To enable CORS in your Blazor Server application, follow these steps: Create a new Blazor Server application with latest .Net support. After creating the application, open the Program.cs file. In this file, you will find the code where the AddCors method is called on the builder.Services object to register the CORS service. Within the AddCors method, a named CORS policy called “NewPolicy” is defined using the options.AddPolicy method. If necessary, you can further configure the CORS policy by providing additional options through the builder parameter in the AddPolicy method. [Program.cs] ... builder.Services.AddCors(options => { options.AddPolicy("NewPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); }); ... app.UseRouting(); app.UseCors("NewPolicy"); app.UseAuthorization(); AllowAnyOrigin—Allows access from any origin. AllowAnyMethod—Access to allow any method. AllowAnyHeader—Access to allow any header in a request. Note: Call the UseCors method between the UseRouting and UseAuthorization methods.
How do you bundle and minify the CSS and JS files in Blazor applications?
Bundling is the process of combining multiple files into a single file. Minifying is the process of removing unnecessary data such as comments and extra spaces, as well as converting a large variable name into a smaller name without affecting its functionalities. To bundle and minify the CSS and JS files in a Blazor application, follow these steps: Install the BuildBundlerMinifier NuGet package and reference it in the .csproj file, as shown. [.csproj] <Project Sdk="Microsoft.NET.Sdk.Web"> …………… <ItemGroup> <PackageReference Include="BuildBundlerMinifier" Version="3.2.449" /> …………… </ItemGroup> </Project> Create a new .json file named bundleconfig.json and add the following code to bundle and minify the CSS and JS files. [bundleconfig.json] [ { "outputFileName": "wwwroot/css/bundle.min.css", "inputFiles": [ "wwwroot/css/app.css", "wwwroot/css/site.css" ] }, { "outputFileName": "wwwroot/scripts/bundle.min.js", "inputFiles": [ "wwwroot/scripts/core.js", "wwwroot/scripts/index.js" ], "minify": { "enabled": true, "renameLocals": true }, "sourceMap": false } ] After you build your application, the bundled and minified files are generated as shown in the following image. You can reference these files in your application based on the requirement. View Sample in GitHub
What is the purpose of the “AddDefaultPolicy” and “AddPolicy” methods in the CORS configuration?
The AddDefaultPolicy method allows you to add a new policy to the CORS configuration and make it the application’s default. In the Program.cs file, you can call the AddCors method to add the cross-origin resource sharing services to the service collection. To add a default policy to the configuration, you can call the AddDefaultPolicy within the AddCors method. Since you are using the default policy, there is no need to include the policy name in the UseCors method, as shown. [Program.cs] The AddPolicy method allows you to add a custom policy to the CORS configuration and give it a name for identification. In the Program.cs file, to add a user-defined (custom) policy to the configuration, you can call AddPolicy within the AddCors method. [Program.cs] Then, you should call the UseCors method and pass the user-defined (custom) policy name to add the CORS middleware to the application pipeline. [Progaram.cs] Note: Call the UseCors method between the UseRouting and UseAuthorization methods.