Search code examples
javascriptasp.net-coreblazorcomponents.net-8.0

Bundle a Blazor Component's JavaScript


Blazor components support CSS bundling and cohesiveness: Foo.razor would have Foo.razor.css, which will: a) enjoy CSS isolation; b) bundle into {ASSEMBLY NAME}.styles.css.

What I'm after is a similar mechanism for component-scoped JavaScript.

I don't want to put generic functions in the global scope (window) and call them via jsComponentInitializers as demonstrated here, mainly because it breaks the idea of components as cohesive units; and also since if I put my JavaScript code within the .razor file, I end up having the same code repeated and scattered throughout the page, as I use multiple instances of that component.

The rendering mode is Static server-side rendering (SSR).

Is there a way to use JavaScript in a custom Blazor component such that it bundles into something similar to {ASSEMBLY NAME}.scripts.js, or any other form, and exists only once? (note that I still want to be able to distinguish between component instances in a similar way to the way CSS is component-isolated)


Solution

  • Blazor doesn't support JavaScript isolation in the same way it does for CSS. However, you can use a JavaScript bundler to compile multiple files into a single file. To do this, download the Bundler extension in Visual Studio 2022. Then, create a configuration file in your root directory with the following content:

    {
        "outputFileName": "wwwroot/js/bundle.min.js",
        "inputFiles": [
          "wwwroot/js/ts/file1.js",
          "wwwroot/js/ts/file2.js",
          "wwwroot/js/ts/file3.js",
          "wwwroot/js/ts/file4.js"
        ],
        "minify": {
          "enabled": true,
          "outputMode": "singleLine",
          "commentMode": "important",
          "adjustRelativePaths": true,
          "renameLocals": true,
          "gzip": true
        },
        "sourceMap": true
      }