在 cshtml 文件 asp.net 核心中缩小 javascript

Minify javascript in cshtml file asp.net core

有没有办法缩小 .cshtml 文件中“@section Scripts”标记内的 javascript?

有很多选项,没有更多详细信息,很难回答哪个最适合您。

None 这些解决方案将解析 Razor 语法,或者能够自行在 cshtml 文件的脚本 @section 块中找到您的 JS 代码。如果你需要缩小代码,你应该把它拉到一个 JS 文件中并用 <script src="..">

引用它

选项

Visual Studio 工具:BundlerMinifier。使用此工具,您可以捆绑和缩小 CSS 和 JS 文件。作为一次性操作(右键单击 -> 缩小文件)或者您可以创建一个 bundleconfig.json

Link: https://marketplace.visualstudio.com/items?itemName=MadsKristensen.BundlerMinifier

Note: This tool is included by default with VS 2019, and only needs to be installed via the marketplace on VS 2017 or prior

其他途径通常涉及 NodeJs

通常,Asp.net 核心应用程序使用 BuildBundlerMinifier package to bundle and minify static assets (JavaScript, CSS, and images files). So, to minify the JavaScript scripts within the @section Scripts tag, you have to extract the scripts into an external script file, then using BuildBundlerMinifier to minify the JS file. More detail information about using BuildBundlerMinifier, see Bundle and minify static assets in ASP.NET Core

此外,你也可以尝试使用一些开源包来缩小内联JS。如:WebMarkupMin.

您可以通过 NuGet 包管理器安装此包(根据您的应用程序版本 select 包版本):

然后,在Startup.cs文件中,在Configure和ConfigureServices方法中添加app.UseWebMarkupMin();services.AddWebMarkupMin();,代码如下:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();

        services.AddWebMarkupMin(
       options =>
       {
           options.AllowMinificationInDevelopmentEnvironment = true;
           options.AllowCompressionInDevelopmentEnvironment = true;
       })
       .AddHtmlMinification(
           options =>
           {
               options.MinificationSettings.RemoveRedundantAttributes = true;
               options.MinificationSettings.RemoveHttpProtocolFromAttributes = true;
               options.MinificationSettings.RemoveHttpsProtocolFromAttributes = true;
           })
       .AddHttpCompression();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();

        //Required using WebMarkupMin.AspNetCore5;
        app.UseWebMarkupMin();

        app.UseStaticFiles();

        app.UseRouting();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });
    }

之后 JavaScript 脚本被缩小。截图如下:

之前:

之后: