Blazor

4 Easy Steps to Embed a JavaScript Control into a Blazor App

Blazor is an open-source, single-page web application development framework developed by Microsoft. Even though it depends on NuGet packages, it also supports the use of npm packages.

npm contains a broader range of libraries, frameworks, and web components. Furthermore, the web components are downloaded as independent modules and styles. npm allows us to construct the required control with only the necessary modules and CSS, resulting in less memory utilization.

In this blog, we will see how to import npm packages as well as declare and embed a JavaScript control into a Blazor application in detail. To demonstrate, we will download the Syncfusion JavaScript Spreadsheet npm package and add it to the Razor page.

Step 1: Initializing npm and other necessary packages.

To begin, launch Visual Studio and create a Blazor WebAssembly application. The npm option is not available by default in this new application. So, create a new folder named npm_packages to initialize the npm and other options to hold the downloaded packages and the control definition.

To initialize npm and download the prerequisite packages, run the command prompt and navigate to the npm_packages folder directory. Then, execute the following commands in the specified order:

  1. Install npm. This will automatically create the package.json file inside the npm_packages folder.
  2. Install the webpack utility. This will assist in module bundler and JavaScript conversion.
  3. Install the latest NPM package of the Syncfusion JavaScript Spreadsheet control.
    npm init -y
    npm install webpack webpack-cli –save-dev
    npm install @syncfusion/ej2-spreadsheet

Step 2: Initializing and defining the Syncfusion JavaScript Spreadsheet control.

Once npm is configured, you can see the package.json file inside the npm packages folder. Now, create a folder named src within it create the index.js file. Then, import the Syncfusion JavaScript Spreadsheet modules and define the widget in the index.js file.

To define the Syncfusion JavaScript Spreadsheet control, first, add a div container with the ID element to the Index.razor page.

Refer to the following code.

[Index.razor]

@page "/"

<h2>Syncfusion JavaScript Spreadsheet control</h2>

<div id="element"></div>

Then, define the control in the index.js file with the necessary module(s) and add it to the div container using its ID.

[index.js]

import { Spreadsheet } from '@syncfusion/ej2-spreadsheet';

// Define the Syncfusion JavaScript Spreadsheet component.
var numberFormat = '$#,##0.00';
var spreadsheet = new Spreadsheet({
    sheets: [
        {
            name: 'Monthly Budget',
            selectedRange: 'D13',
            rows: [
                {
                    cells: [
                        { value: 'Category', style: { fontWeight: 'bold', textAlign: 'center' } },
                        { value: 'Planned cost', style: { fontWeight: 'bold', textAlign: 'center' } },
                        { value: 'Actual cost', style: { fontWeight: 'bold', textAlign: 'center' } },
                        { value: 'Difference', style: { fontWeight: 'bold', textAlign: 'center' } }
                    ]
                },
                {
                    cells: [
                        { value: 'Food' },
                        { value: '7000', format: '$#,##0.00' },
                        { value: '8120', format: '$#,##0.00' },
                        { formula: '=B2-C2', format: numberFormat }
                    ]
                },
                {
                    cells: [
                        { value: 'Loan' },
                        { value: '1500', format: '$#,##0.00' },
                        { value: '1500', format: '$#,##0.00' },
                        { formula: '=B3-C3', format: numberFormat }
                    ]
                },
                {
                    cells: [
                        { value: 'Medical' },
                        { value: '300', format: '$#,##0.00' },
                        { value: '0', format: '$#,##0.00' },
                        { formula: '=B4-C4', format: numberFormat }
                    ]
                },
                {
                    cells: [
                        { value: 'Clothing' },
                        { value: '400', format: '$#,##0.00' },
                        { value: '140', format: '$#,##0.00' },
                        { formula: '=B5-C5', format: numberFormat }
                    ]
                },
                {
                    cells: [
                        { value: 'Education' },
                        { value: '900', format: '$#,##0.00' },
                        { value: '750', format: '$#,##0.00' },
                        { formula: '=B6-C6', format: numberFormat }
                    ]
                },
                {
                    cells: [
                        { value: 'Insurance' },
                        { value: '30', format: '$#,##0.00' },
                        { value: '30', format: '$#,##0.00' },
                        { formula: '=B7-C7', format: numberFormat }
                    ]
                },
                {
                    cells: [
                        { value: 'Utilities' },
                        { value: '130', format: '$#,##0.00' },
                        { value: '160', format: '$#,##0.00' },
                        { formula: '=B8-C8', format: numberFormat }
                    ]
                },
                {
                    cells: [
                        { value: 'Enterainment' },
                        { value: '500', format: '$#,##0.00' },
                        { value: '730', format: '$#,##0.00' },
                        { formula: '=B9-C9', format: numberFormat }
                    ]
                },
                {
                    cells: [
                        { value: 'Maintainance' },
                        { value: '50', format: '$#,##0.00' },
                        { value: '70', format: '$#,##0.00' },
                        { formula: '=B10-C10', format: numberFormat }
                    ]
                },
                {
                    cells: [
                        { value: 'Transportation' },
                        { value: '250', format: '$#,##0.00' },
                        { value: '400', format: '$#,##0.00' },
                        { formula: '=B11-C11', format: numberFormat }
                    ]
                },
                {
                    cells: [
                        { value: 'Gifts/Donations' },
                        { value: '0', format: '$#,##0.00' },
                        { value: '100', format: '$#,##0.00' },
                        { formula: '=B12-C12', format: numberFormat }
                    ]
                },
                {
                    cells: [
                        { index: 2, value: 'Total Difference:', style: { fontWeight: 'bold', textAlign: 'right' } },
                        { formula: '=D2+D12', format: numberFormat, style: { fontWeight: 'bold' } }
                    ]
                }
            ],
            columns: [
                { width: 110 }, { width: 115 }, { width: 110 }, { width: 100 }
            ]
        }
    ]
});

// Render the defined spreadsheet.
spreadsheet.appendTo('#element');

Step 3: Adding build script to the application.

Now, let’s include the following build script in the package.json file. It uses webpack to bundle the JavaScript file. This script tells the 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.

Refer to the following code.

[package.json]

"scripts": {
  "build": "webpack ./src/index.js --output-path ../wwwroot/js --output-filename index.bundle.js"
  }

To bundle the module(s) and control definition periodically, we have to add a prebuild step to the *.csproj file. Bundling occurs when you build or rebuild 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>

Step 4: Adding necessary JS and CSS for the control.

Finally, when the application is built, the index.bundle.js file will be generated. We have to add it to the application via the index.html file in the wwwroot folder. Copy and paste the appropriate CSS stylesheet from the node_modules\@syncfusion\~ to the wwwroot\css folder path, then add it to the application via the index.html file.

Note: Since it is a JavaScript control, we have to initialize the div container within the Index.razor file before the scripts containing the module(s) and definition. To achieve this, make the following changes to the index.html code, which will load the scripts after the Blazor starts.

[index.html]

<head>
    
    ......
    ......

    <link href="css/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="css/ej2-inputs/styles/material.css" rel="stylesheet" />
    <link href="css/ej2-buttons/styles/material.css" rel="stylesheet" />
    <link href="css/ej2-splitbuttons/styles/material.css" rel="stylesheet" />
    <link href="css/ej2-lists/styles/material.css" rel="stylesheet" />
    <link href="css/ej2-navigations/styles/material.css" rel="stylesheet" />
    <link href="css/ej2-popups/styles/material.css" rel="stylesheet" />
    <link href="css/ej2-dropdowns/styles/material.css" rel="stylesheet" />
    <link href="css/ej2-grids/styles/material.css" rel="stylesheet" />
    <link href="css/ej2-spreadsheet/styles/material.css" rel="stylesheet" />

    <script src="js/index.bundle.js"></script>

</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>

Now, run the application. Then, you can see the JavaScript Spreadsheet control in your Blazor WebAssembly application.

Refer to the following screenshot.

Embedding a JavaScript Spreadsheet into Blazor app

References

For more information, refer to the following reference links:

Conclusion

Thanks for reading! In this blog post, we have seen how to embed a JavaScript control into a Blazor application using npm packages. As the npm packages allow us to construct the required control with only the necessary modules and CSS, we can considerably reduce memory utilization. Try out the steps given in this blog post and leave your feedback in the comments section given below!

The Syncfusion Blazor suite offers over 70 components that work with both Blazor server- side and client-side (Blazor WebAssembly) projects seamlessly. Use them to build astonishing applications!

For existing customers, the newest version of Essential Studio is available for download from the License and Downloads page. If you are not yet a Syncfusion customer, you can try our 30-day free trial to check out the available features.

For questions, you can contact us through our support forumDirect-Trac, or feedback portal. We are always happy to assist you!

Related blogs

Hari Venkatesh E

Hari Venkatesh works as a Product Manager in Syncfusion, a UI component-based company. He who works with diversified .NET platforms, specifically in Web Technology and Windows Forms, to provide technical guidance and solutions.