使用缩小的JS和CSS的公共条件Razor视图

时间:2015-02-08 22:30:55

标签: asp.net-mvc razor asp.net-mvc-5 razorengine

我正在使用ASP.NET MVC 5来开发我的网站。我正在使用Grunt来缩小我的CSS和JS。一切正常,但如果我正在进行发布(发布模式)或我正在调试(我需要清楚地阅读我的CSS和JS),我需要更改文件的路由源。

这样的事情:

  

[调试模式]

<script src="scripts/myscript.js"></script>
  

[相对模式或公共模式]

<script src="dist/myscript.min.js"></script>

我已经在StackOverflow(Razor view engine, how to enter preprocessor(#if debug))上阅读了这篇文章,我不喜欢建议的解决方案,因为我认为(不确定)加载的Razon View将会如果它处于发布或调试模式,请始终在Production Server中检查,我认为没有必要。

有人可以确认我是对的吗?我是否需要手动进行更改?还有其他解决办法吗?

谢谢!此致!!

2 个答案:

答案 0 :(得分:6)

您可以实现此目的的一种方法是在http上下文中检查调试模式。

@if (HttpContext.Current.IsDebuggingEnabled)
{
    <script src="scripts/myscript.js"></script>
}
else
{
    <script src="dist/myscript.min.js"></script>
}

答案 1 :(得分:0)

更新后的答案

感谢Shoe,我了解了环境标签帮助程序的存在,因此,我们现在可以像这样使用它来代替以前的手动解决方法:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"]</title>
    <environment include="Development">
        <link rel="stylesheet" href="~/css/sasw.css" asp-append-version="true" />
    </environment>
    <environment exclude="Development">
        <!-- Google Analytics here for example -->
        <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
    </environment>
</head>

旧答案 适用于Razor页面(也应与Razor视图一起使用)的解决方案(dotnet核心3.1+)可能是注入IWebHostEnvironment并根据当前环境(由全局变量ASPNETCORE_ENVIRONMENT定义)有条件地呈现 在您的_Layout.cshtml

@using Microsoft.Extensions.Hosting
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment Env
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"]</title>
    @if (Env.IsDevelopment())
    {
        <link rel="stylesheet" href="~/css/sasw.css" asp-append-version="true" />
    }
    else
    {
        <!-- Google Analytics here for example -->
        <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
    }
</head>

此解决方案可与bundleconfig.json定义的bundle and minification策略很好地配合使用

在我的情况下,bundleconfig.json如下所示:

[
  {
    "outputFileName": "wwwroot/css/site.min.css",
    "inputFiles": [
      "wwwroot/css/sasw.css"
    ]
  },
  {
    "outputFileName": "wwwroot/js/site.min.js",
    "inputFiles": [
      "wwwroot/js/sasw.js"
    ],
    "minify": {
      "enabled": true,
      "renameLocals": true
    },
    "sourceMap": false
  }
]

我添加了一个名为BuildBundlerMinifier的nuget,它自动缩小并捆绑js和css,并将缩小后的版本与原始版本放置在同一文件夹中。

PS:请记住忽略(例如:在.gitignore*.min.js*.min.css,如果您采用相同的方法,则使构建过程每次都生成一个新的而不提交源控制。