简体   繁体   English

在运行时为 ASP.NET 核心缩小动态生成的 JavaScript

[英]Minify dynamically generated JavaScript at runtime for ASP.NET Core

In ASP.NET MVC 5 you would achieve this by:在 ASP.NET MVC 5 中,您可以通过以下方式实现:

public ActionResult DynamicJs()
{
  // dynamically generated
  string javaScript = new Minifier().MinifyJavaScript("alert('Hello world!');");

  // returns minified javaScript
  return JavaScript(javaScript);
}

The Minifier class was a member of Microsoft.Ajax.Utilities, which you would get from the WebGrease Nuget package. Minifier class 是 Microsoft.Ajax.Utilities 的成员,您可以从 WebGrease Nuget ZEFE907A8DZFDE1DA59CZ.Utilities 获得。

However, in ASP.NET Core this package is not available for .NET Core and many are using the BundlerMinifier.Core package by Mads Kristensen for minification. However, in ASP.NET Core this package is not available for .NET Core and many are using the BundlerMinifier.Core package by Mads Kristensen for minification. https://www.nuget.org/packages/BundlerMinifier.Core/3.2.449 https://www.nuget.org/packages/BundlerMinifier.Core/3.2.449

How can I achieve the same result in ASP.NET Core?如何在 ASP.NET 内核中获得相同的结果?

NUglify is the underlying dependency for BundlerMinifier.Core that does all the heavy lifting. NUglify 是 BundlerMinifier.Core 的底层依赖项,它完成了所有繁重的工作。

You can use it to achieve the same result.您可以使用它来实现相同的结果。

//dynamically generated
string javaScript = "alert('Hello world!');";

//set ContentType as the JavaScript() object is not available in .NET Core
ContentResult result = new ContentResult
{
  ContentType = "application/javascript", 
  Content = NUglify.Uglify.Js(javaScript).Code
};
        
return result;

Uglify also has methods for CSS and HTML. Uglify 也有 CSS 和 HTML 的方法。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM