受欢迎的博客标签

 

This post is about Bundling and Minification in ASP.NET Core. Bundling and minification are two techniques you can use in ASP.NET to improve page load performance for your web application. Bundling combines multiple files into a single file. Minification performs a variety of different code optimizations to scripts and CSS, which results in smaller payloads. In ASP.NET Core RTM release Microsoft introduced “BundlerMinifier.Core” tool which will help you to bundle and minimize Javascript and style sheet files. Unlike previous versions MVC, the bundling and minification is happening on development time not in runtime. To use “BundlerMinifier.Core” first you need to add reference of BundlerMinifier.Core in the project.json tools section.

Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <MvcRazorCompileOnPublish>false</MvcRazorCompileOnPublish>
  </PropertyGroup>

  <ItemGroup>   
    <DotNetCliToolReference Include="BundlerMinifier.Core" Version="3.2.447" />   
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\..\Libraries\Nop.Core\Nop.Core.csproj" />   
  </ItemGroup>

</Project>

 

Now you need to specify the Javascript and stylesheet files for bundling and minification. You can do this by adding “bundleconfig.json” file. The name can be changed, but if the filename is bundleconfig.json, it will bundle command will take it automatically. Here is a minimal bundleconfig.json file.

[
  {
    "outputFileName": "wwwroot/css/site.min.css",
    "inputFiles": [
      "wwwroot/css/site.css"
    ]
  },
  {
    "outputFileName": "wwwroot/js/site.min.js",
    "inputFiles": [
      "wwwroot/js/site.js"
    ],
    "minify": {
      "enabled": true,
      "renameLocals": true
    },
    "sourceMap": false
  },
  {
    "outputFileName": "wwwroot/js/semantic.validation.min.js",
    "inputFiles": [
      "wwwroot/js/semantic.validation.js"
    ],
    "minify": {
      "enabled": true,
      "renameLocals": true
    }
  }
]

 

The file is self explantory, you can specify multiple file in the inputFiles element, which will be combined and minified based on the minify element. Now you can combine and minify using “dotnet bundle” command. Here is the output when I run the dotnet bundle command on my MVC project.

dotnet restore
dotnet bundle

output

Bundling with configuration from \src\Presentation\Nop.Web\bundleconfig.json
Processing wwwroot/css/site.min.css
Processing wwwroot/js/site.min.js

There are few more commands also available with dotnet bundle tool.

dotnet bundle clean - Executing dotnet bundle clean will delete all output files from disk.
dotnet bundle watch - To automatically run the bundler when input files change, call dotnet bundle watch. This will monitor any file changes to input files in the working directory and execute the bundler automatically.
dotnet bundle help - Get help on how to use the CLI.