Chuyển đến nội dung chính

ASP.NET Core: Bundling và Minification CSS và JS Files

Khi xây dựng một ứng dụng web hiện đại với ASP.NET Core, tốc độ tải trang là yếu tố sống còn. Để tối ưu hóa hiệu suất cho các static assets như file CSS và JavaScript, chúng ta có hai kỹ thuật cực kỳ hiệu quả: Bundling (Gộp file)Minification (Nén file). 

Bundling và Minification là gì?

Bundling (Gộp file) là gì?

Bundling là quá trình "gói" tất cả các file CSS hoặc JavaScript của bạn lại thành một file duy nhất. Thay vì trình duyệt phải gửi 10 yêu cầu riêng biệt đến máy chủ để tải 10 file, nó chỉ cần gửi một yêu cầu duy nhất. Việc giảm thiểu số lượng yêu cầu đến máy chủ là một trong những yếu tố quan trọng nhất giúp cải thiện thời gian tải trang và đạt điểm cao hơn trên các công cụ đo lường hiệu suất như Google PageSpeed Insights.

Minification (Nén file) là gì?

Minification là quá trình nén các file CSS và JavaScript bằng cách loại bỏ tất cả những thứ không cần thiết cho việc thực thi code, chẳng hạn như khoảng trắng, ngắt dòng và các đoạn comment. Lợi ích của việc nén file rất đơn giản: nó làm giảm đáng kể kích thước file. Điều này đồng nghĩa với việc trình duyệt cần tải về ít dữ liệu hơn, giúp trang web của bạn tải nhanh hơn nữa.

Khi kết hợp, hai kỹ thuật này tạo ra một file duy nhất, siêu nhỏ gọn, mang lại hiệu suất tối ưu cho end user.

Ở ví dụ sau, mình minh họa bằng code ASP.NET Core, nếu bạn vẫn xài ASP.NET MVC thì tham khảo bài viết sau: AngularJs: Bundling và Minification

LigerShark

LigerShark.WebOptimizer.Core là một thư viện mã nguồn mở giúp thực hiện bundling và minification trong ASP.NET Core. 

Github: https://github.com/ligershark/WebOptimizer 

Ưu điểm:

  • Hỗ trợ gộp nhiều file JS/CSS.
  • Hỗ trợ minify tự động.
  • Có thể dùng trong cả Development và Production.
  • Cấu hình đơn giản, không cần task runner phức tạp như Gulp/Grunt.

Cài đặt

dotnet add package LigerShark.WebOptimizer.Core
Chuẩn bị các file css js sau:
wwwroot/
├── css/
│   ├── style1-layout.css
│   └── style2-components.css
└── js/
    ├── script1-events.js
    └── script2-helpers.js

Để giữ cho Program.cs gọn gàng, chúng ta sẽ tạo một Extension Method để quản lý toàn bộ cấu hình bundling.

  1. Tạo thư mục Extensions trong dự án.

  2. Tạo file WebOptimizerExtensions.cs bên trong thư mục đó với nội dung sau 

    namespace BundlerMinifierSample.WebExtensions;
    
    public static class WebOptimizerExtensions
    {
        public static IServiceCollection AddCustomWebOptimizer(
            this IServiceCollection services)
        {
            services.AddWebOptimizer(pipeline =>
            {
                // Create CSS bundle
                pipeline.AddCssBundle("/css/custom-bundle.css",
                    "css/style1-layout.css",
                    "css/style2-components.css");
    
                // Create JS bundle
                pipeline.AddJavaScriptBundle("/js/custom-bundle.js",
                    "js/script1-events.js", 
                    "js/script2-helpers.js"); 
            });
    
            return services;
        }
    }
    
    Mở file Program.cs để thêm cấu hình sau:
    // 1. Register WebOptimizer
    builder.Services.AddCustomWebOptimizer();
    
    builder.Services.AddControllersWithViews();
    // ... your code ...
    app.UseWebOptimizer();
    
    app.UseStaticFiles();
    // ... your code ...
    
    File layout.cshtml
    @addTagHelper *, WebOptimizer.Core
    @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>@ViewData["Title"] - BundlerMinifierSample</title>
        <script type="importmap"></script>
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
        <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
        <environment include="Development">
            <link rel="stylesheet" href="~/css/style1-layout.css" asp-append-version="true" />
            <link rel="stylesheet" href="~/css/style2-components.css" asp-append-version="true" />
        </environment>
        <environment exclude="Development">
            <link rel="stylesheet" href="~/css/custom-bundle.css" asp-append-version="true" />
        </environment>
    </head>
    
    <body>
        <header>
            <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
                <div class="container-fluid">
                    <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">BundlerMinifierSample</a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse"
                        aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                        <ul class="navbar-nav flex-grow-1">
                            <li class="nav-item">
                                <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
        </header>
        <div class="container">
            <main role="main" class="pb-3">
                <div class="content-wrapper mb-4">
                    <h4>Interactive Component Demo</h4>
                    <p>This section demonstrates the bundled and minified CSS and JavaScript files.</p>
                    <button id="change-message-btn" class="interactive-button">Click Me</button>
                    <div id="status-message">Status: Waiting for interaction...</div>
                </div>
                @RenderBody()
            </main>
        </div>
    
        <footer class="border-top footer text-muted">
            <div class="container">
                © 2025 - BundlerMinifierSample - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
            </div>
        </footer>
        <script src="~/lib/jquery/dist/jquery.min.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
        <environment include="Development">
            <script src="~/js/script1-events.js" asp-append-version="true"></script>
            <script src="~/js/script2-helpers.js" asp-append-version="true"></script>
        </environment>
        <environment exclude="Development">
            <script src="~/js/custom-bundle.js"></script>
        </environment>
        @await RenderSectionAsync("Scripts", required: false)
    </body>
    
    </html>  

Khi ở môi trường Development: WebOptimizer sẽ tự động chèn các thẻ <link><script> riêng lẻ trỏ đến các file gốc của bạn. Điều này giúp bạn gỡ lỗi (debug) cực kỳ dễ dàng trong trình duyệt.

Khi triển khai (Production): WebOptimizer sẽ gộp, nén và phục vụ một file duy nhất cho mỗi bundle, đồng thời tự động thêm phiên bản vào URL để tránh lỗi cache khi bạn cập nhật code.

Source code: https://www.mediafire.com/file/gnh4wghroulym0e/BundlerMinifierSample.rar/file 

Nhận xét

Bài đăng phổ biến từ blog này

[ASP.NET MVC] Authentication và Authorize

Một trong những vấn đề bảo mật cơ bản nhất là đảm bảo những người dùng hợp lệ truy cập vào hệ thống. ASP.NET đưa ra 2 khái niệm: Authentication và Authorize Authentication xác nhận bạn là ai. Ví dụ: Bạn có thể đăng nhập vào hệ thống bằng username và password hoặc bằng ssh. Authorization xác nhận những gì bạn có thể làm. Ví dụ: Bạn được phép truy cập vào website, đăng thông tin lên diễn đàn nhưng bạn không được phép truy cập vào trang mod và admin.

ASP.NET MVC: Cơ bản về Validation

Validation (chứng thực) là một tính năng quan trọng trong ASP.NET MVC và được phát triển trong một thời gian dài. Validation vắng mặt trong phiên bản đầu tiên của asp.net mvc và thật khó để tích hợp 1 framework validation của một bên thứ 3 vì không có khả năng mở rộng. ASP.NET MVC2 đã hỗ trợ framework validation do Microsoft phát triển, tên là Data Annotations. Và trong phiên bản 3, framework validation đã hỗ trợ tốt hơn việc xác thực phía máy khách, và đây là một xu hướng của việc phát triển ứng dụng web ngày nay.

Tổng hợp một số kiến thức lập trình về Amibroker

Giới thiệu về Amibroker Amibroker theo developer Tomasz Janeczko được xây dựng dựa trên ngôn ngữ C. Vì vậy bộ code Amibroker Formula Language sử dụng có syntax khá tương đồng với C, ví dụ như câu lệnh #include để import hay cách gói các object, hàm trong các block {} và kết thúc câu lệnh bằng dấu “;”. AFL trong Amibroker là ngôn ngữ xử lý mảng (an array processing language). Nó hoạt động dựa trên các mảng (các dòng/vector) số liệu, khá giống với cách hoạt động của spreadsheet trên excel.