【问题标题】:Can you minify javascript at runtime with Microsoft Ajax minifier?您可以在运行时使用 Microsoft Ajax 缩小器缩小 javascript 吗?
【发布时间】:2014-01-14 16:43:35
【问题描述】:

我无法访问我们的构建环境,但我的项目中有 AjaxMin DLL。我想知道我是否可以在我的 MVC-4 项目中使用我的包并缩小我的 javascript。

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js"));

我希望在添加捆绑包后,我可以在 C# 代码中自行缩小文件,而不是在源代码管理中使用单独的缩小项目文件。

【问题讨论】:

  • 当您在发布模式下部署时,通过使用 Bundles ASP.NET 会自动缩小您的 *.js 文件...为什么要手动缩小文件?
  • @Lucian,它还会将所有 javascript 合并到一个文件中吗?
  • @Simsons 是的,只要你将它们捆绑在同一个......捆绑中:) :bundles.Add(new ScriptBundle("~/bundles/all").Include("~/js1.js","~/js2.js"));。这会将 js1.js 和 js2.js 缩小并合并为一个文件,路径为 /bundles/all

标签: javascript asp.net minify


【解决方案1】:

不确定这是否是您所需要的,但在 ASP.NET 4.5 中,当您在非调试模式下部署网站时,打包和缩小是开箱即用的:

在文件:~/App_Start/BundleConfig.cs 中,指定捆绑包:

public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/all").Include(
                    "~/Scripts/jquery-{version}.js",
                    "~/Scripts/jquery.validate*",
                    "~/Scripts/bootstrap.js",
                    "~/Scripts/respond.js"));

        bundles.Add(new StyleBundle("~/Content/css").Include(
                  "~/Content/bootstrap.css",
                  "~/Content/site.css"));
    }

并且在您的 ~/Views/Shared/_Layout.cshtml 中使用指定的捆绑包:

<html>
  <head>
    <!-- other head declarations -->

    <!-- use the css bundle -->
    @Styles.Render("~/Content/css")
  </head>
  <body>
    <!-- other body declarations -->

    <!-- use the javascript bundle -->
    @Scripts.Render("~/bundles/all")
  </body>
</html>

现在,当您在 Release 配置中发布您的 ASP.MVC 站点时,CSS 和 JavaScript 将各自捆绑并缩小到它们自己的单个 css 和 js 文件中。

  • CSS 将从以下位置下载:/Content/css?VoSYW5j1afpgB_oENS5Bi。
  • 将从以下位置下载 JavaScript:/bundles/all?zWZPUr7GJrRS_Ux89ubfE81

哈希字符串用于防止构建之间的缓存。

一切都很详细here,真的值得一看。

【讨论】:

    猜你喜欢
    • 2011-01-18
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多