Requirements: In previous .NET Framework MVC projects, JS, CSS can be bundled and compressed using Microsoft's Microsoft.AspNet.Web.Optimization library. After using ASP.NET Core, how do I bundle and compress existing JS and CSS files?
The .NET Framework project references the following:
Sample code:
binding
Bundling combines multiple files into a single file. Bundling reduces the number of server requests required to render a web asset, such as a web page. You can create as many individual bundles as you want specifically for CSS, JavaScript, and more. Fewer files mean from the browser to the server or from the service that provides the applicationFewer HTTP requests。 This improves homepage loading performance.
compress
Minify removing unnecessary characters from your code without changing functionality. The result wasThe size of requested resources, such as CSS, images, and JavaScript files, is significantly reduced。 Common side effects of minification include shortening variable names to one character and removing comments and unnecessary spaces. At the same time, it canConfuse the code, which is not conducive to other competitors reading our source code.
Performance gains from bundling and compression
The following table outlines the differences between loading assets individually and using bundling and minification:
It saves traffic and improves loading speed in terms of network transport, while also reducing HTTP requests and improving loading speed.
For HTTP request headers, the browser is very detailed. When bundled, the total bytes sent metric is significantly reduced. Load times show significant improvements, but this example runs locally. Bundling and minification can be combined with assets transported over the network to achieve higher performance gains.
ASP.NET Core does not have its own bundled and compressed solution, and needs to use a solution provided by a third party, this article uses "LigerShark.WebOptimizer.Core(The library eventually called.)NUglifyImplement JS and CSS handling), GitHub address:The hyperlink login is visible.
First, create a new project ASP.NET Core 6 and run the following command to reference:
Create a new static folder in the project wwwroot to store the test css and js files. Create a new CSS and JS file, as shown below:
Modify the Program.cs file and add the WebOptimizer service and middleware, the main code is as follows:
When we try to start the project, we find that the comments of both CSS and JS code have been deleted, and the files have been compressed, and some variables in JS have been reduced to a single letter, as shown in the figure below:
Then create a new js file from the static folder to test the bundling function.Bundle test.js and test2.js into a single common.js file(and does not generate a common.js physical file), the configuration code is as follows:
The renderings are as follows:
Reference:
The hyperlink login is visible.
The hyperlink login is visible.
|