Đặt JavaScript ở đâu trong dao cạo?

Việc phát hành. NET 6 đã giải phóng một làn sóng ASP. NET Core dành cho cộng đồng phát triển. Một số tính năng nhận được nhiều sự chú ý, trong khi một số tính năng khác hoạt động âm thầm dưới radar. Một trong những tính năng mà tôi mới phát hiện gần đây là cách ly CSS và các tệp JavaScript được sắp xếp với một thành phần, chế độ xem MVC hoặc Trang dao cạo. Thật không may, trong khi tính năng cách ly CSS hoạt động rất ấn tượng, thì tính năng sắp xếp thứ tự JavaScript lại không hoàn thiện. Với tính năng cách ly CSS, bạn có thể thêm tệp .css bên cạnh ASP của mình. NET Core và ASP. NET Core sẽ xử lý các kiểu của bạn thành một tệp CSS cụ thể. Tuy nhiên, bạn vẫn cần tham chiếu từng tệp được sắp xếp trong chế độ xem của mình bằng các tệp JavaScript

Tôi nghĩ chúng ta có thể làm tốt hơn. Chúng ta sẽ khám phá cách viết TagHelper chỉ hoạt động trong bài đăng này. Chúng tôi có thể nhập các tệp JavaScript được sắp xếp theo thứ tự bằng cách sử dụng một trình trợ giúp thẻ duy nhất với giải pháp của tôi tùy thuộc vào việc tệp có tồn tại hay không. Bắt đầu nào

Các tệp JavaScript được sắp xếp trong JavaScript

ASP. NET Core cho phép chúng tôi lưu trữ các tệp JavaScript cùng với các chế độ xem Dao cạo và các thành phần Dao cạo. Tính năng này cải thiện khả năng suy luận về ứng dụng của chúng tôi bằng cách giữ cho tất cả các yếu tố càng cục bộ càng tốt. Dưới đây là một số ví dụ lấy từ

Sắp xếp các tệp JS bằng cách sử dụng các quy ước mở rộng tên tệp sau

  • Trang của ứng dụng Razor Pages và chế độ xem của ứng dụng MVC. .cshtml.js. ví dụ
    • Pages/Index.cshtml.js cho trang Chỉ mục của ứng dụng Razor Pages tại Pages/Index.cshtml
    • Views/Home/Index.cshtml.js cho chế độ xem Chỉ mục của ứng dụng MVC tại Views/Home/Index.cshtml
  • Các thành phần dao cạo của ứng dụng Blazor.
    
    
    
     append-version="true" />
    
    0. Thí dụ.
    
    
    
     append-version="true" />
    
    1 cho thành phần Chỉ mục tại
    
    
    
     append-version="true" />
    
    2

Tóm lại, tất cả các tệp JavaScript được đối chiếu với các đối tác Razor của chúng đều có thể truy cập được từ ứng dụng khách. Nhược điểm là bạn cần nhớ tham chiếu từng tệp trong chế độ xem hoặc thành phần Razor gốc của mình

@section Scripts { <script src="~/Pages/Index.cshtml.js">script> }

Sử dụng các phần cũng có thêm gánh nặng quản lý chúng trên




 append-version="true" />
3 của bạn. Ugh, nếu chỉ có một cách tốt hơn?

View Script Tag Helper tự động thêm các tập lệnh được sắp xếp

Với ASP. NET Core, chúng ta có thể xây dựng một số trình trợ giúp thẻ hữu ích. Trong trường hợp của chúng ta, hãy xem kết quả cuối cùng




 append-version="true" />

Lưu ý rằng chúng ta có phần tử




 append-version="true" />
4 trong đoạn mã trước, với thuộc tính là



 append-version="true" />
5. Trình trợ giúp thẻ này trước tiên sẽ tìm thấy chế độ xem ASP. NET Core đang cố kết xuất và thử xác định xem có tồn tại tệp JavaScript được sắp xếp theo thứ tự không. Nếu có, nó sẽ tạo ra một thẻ



 append-version="true" />
6 cho trang; . Một phần thú vị khác của mã sau đây là, các tệp có thể được đặt ở các vị trí khác nhau dựa trên việc ứng dụng đang được phát triển hay đã được xuất bản. Điều này có nghĩa là chúng ta phải xem xét cả nội dung gốc và gốc web cho các tệp JavaScript của mình. Cuối cùng, tôi đã thêm tính năng



 append-version="true" />
5 để phù hợp với ASP hiện có. NET Core



 append-version="true" />
8 triển khai

Hãy cùng xem




 append-version="true" />
9

using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.Extensions.FileProviders;

namespace Isolated;

public class ViewScriptTagHelper : TagHelper
{
    private readonly IWebHostEnvironment environment;
    private readonly IFileVersionProvider fileVersionProvider;
    private const string AppendVersionAttributeName = "append-version";

    public ViewScriptTagHelper(IWebHostEnvironment environment, IFileVersionProvider fileVersionProvider)
    {
        this.environment = environment;
        this.fileVersionProvider = fileVersionProvider;
    }

    [ViewContext] 
    public ViewContext? ViewContext { get; set; }
    
    /// 
    /// Value indicating if file version should be appended to src urls.
    /// 
    /// 
    /// A query string "v" with the encoded content of the file is added.
    /// 
    [HtmlAttributeName(AppendVersionAttributeName)]
    public bool? AppendVersion { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        // remove the `page-script` tag if script doesn't exist
        output.TagName = null;
        output.TagMode = TagMode.StartTagAndEndTag;

        var viewPath = ViewContext?.View.Path;
        var src = $"{viewPath}.js";
        
        /* When the app is published, the framework automatically moves the script to the web root.
           So we should check both places, with the content root first for development */
        var fileInfo = environment.ContentRootFileProvider.GetFileInfo(src) ?? 
                       environment.WebRootFileProvider.GetFileInfo(src);

        if (fileInfo is {Exists: true})
        {
            // switch it to script now
            output.TagName = "script";
            output.Content = new DefaultTagHelperContent();
            
            if (AppendVersion == true)
            {
                // people love their cache busting versions
                src = fileVersionProvider.AddFileVersionToPath(src, src);
            }
            
            output.Attributes.Add("src", src);
        }
    }
}

Thêm




 append-version="true" />
9 vào dự án của bạn sẽ cung cấp cho bạn chức năng mới này. Hãy chú ý đến việc đăng ký trình trợ giúp thẻ trong tệp
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.Extensions.FileProviders;

namespace Isolated;

public class ViewScriptTagHelper : TagHelper
{
    private readonly IWebHostEnvironment environment;
    private readonly IFileVersionProvider fileVersionProvider;
    private const string AppendVersionAttributeName = "append-version";

    public ViewScriptTagHelper(IWebHostEnvironment environment, IFileVersionProvider fileVersionProvider)
    {
        this.environment = environment;
        this.fileVersionProvider = fileVersionProvider;
    }

    [ViewContext] 
    public ViewContext? ViewContext { get; set; }
    
    /// 
    /// Value indicating if file version should be appended to src urls.
    /// 
    /// 
    /// A query string "v" with the encoded content of the file is added.
    /// 
    [HtmlAttributeName(AppendVersionAttributeName)]
    public bool? AppendVersion { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        // remove the `page-script` tag if script doesn't exist
        output.TagName = null;
        output.TagMode = TagMode.StartTagAndEndTag;

        var viewPath = ViewContext?.View.Path;
        var src = $"{viewPath}.js";
        
        /* When the app is published, the framework automatically moves the script to the web root.
           So we should check both places, with the content root first for development */
        var fileInfo = environment.ContentRootFileProvider.GetFileInfo(src) ?? 
                       environment.WebRootFileProvider.GetFileInfo(src);

        if (fileInfo is {Exists: true})
        {
            // switch it to script now
            output.TagName = "script";
            output.Content = new DefaultTagHelperContent();
            
            if (AppendVersion == true)
            {
                // people love their cache busting versions
                src = fileVersionProvider.AddFileVersionToPath(src, src);
            }
            
            output.Attributes.Add("src", src);
        }
    }
}
1 của bạn

@using Isolated
@namespace Isolated.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Isolated

Trong trường hợp của tôi, tên dự án và không gian tên của tôi là

using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.Extensions.FileProviders;

namespace Isolated;

public class ViewScriptTagHelper : TagHelper
{
    private readonly IWebHostEnvironment environment;
    private readonly IFileVersionProvider fileVersionProvider;
    private const string AppendVersionAttributeName = "append-version";

    public ViewScriptTagHelper(IWebHostEnvironment environment, IFileVersionProvider fileVersionProvider)
    {
        this.environment = environment;
        this.fileVersionProvider = fileVersionProvider;
    }

    [ViewContext] 
    public ViewContext? ViewContext { get; set; }
    
    /// 
    /// Value indicating if file version should be appended to src urls.
    /// 
    /// 
    /// A query string "v" with the encoded content of the file is added.
    /// 
    [HtmlAttributeName(AppendVersionAttributeName)]
    public bool? AppendVersion { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        // remove the `page-script` tag if script doesn't exist
        output.TagName = null;
        output.TagMode = TagMode.StartTagAndEndTag;

        var viewPath = ViewContext?.View.Path;
        var src = $"{viewPath}.js";
        
        /* When the app is published, the framework automatically moves the script to the web root.
           So we should check both places, with the content root first for development */
        var fileInfo = environment.ContentRootFileProvider.GetFileInfo(src) ?? 
                       environment.WebRootFileProvider.GetFileInfo(src);

        if (fileInfo is {Exists: true})
        {
            // switch it to script now
            output.TagName = "script";
            output.Content = new DefaultTagHelperContent();
            
            if (AppendVersion == true)
            {
                // people love their cache busting versions
                src = fileVersionProvider.AddFileVersionToPath(src, src);
            }
            
            output.Attributes.Add("src", src);
        }
    }
}
2. Đảm bảo cập nhật mã để phù hợp với dự án và không gian tên của bạn

Tôi đã thử nghiệm trình trợ giúp thẻ này với ASP. NET Core MVC và Razor Pages và nó hoạt động trong cả hai trường hợp. Tôi chưa thử nghiệm với các thành phần Razor hoặc Blazor, nhưng tôi nghi ngờ nó sẽ hoạt động

Phần kết luận

Trình trợ giúp thẻ vô cùng mạnh mẽ và việc bổ sung tính năng cách ly CSS và sắp xếp thứ tự JavaScript giúp xây dựng các thành phần trong ASP. NET Core có thể khiến việc xây dựng ứng dụng web trở thành niềm vui. Với trình trợ giúp thẻ trong bài đăng này, bạn sẽ có một yếu tố ít chuyển động hơn để lo lắng trong quá trình phát triển. Tôi hy vọng bạn thích bài viết này. Hãy chia sẻ và nhớ theo dõi tôi trên Twitter @buhakmeh. Và như mọi khi, cảm ơn bạn đã đọc

Đặt JavaScript ở đâu trong trang dao cạo?

Gọi hàm JavaScript từ Razor View . include a