如何使用Gulp与Razor和Layout.cshtml

时间:2015-09-03 04:29:37

标签: asp.net-mvc asp.net-mvc-4 razor gulp

在MVC模板文件中使用Gulp的最佳方法是什么?问题是我的layout.cshtml文件包含指向JavaScript文件的链接,gulp需要修改这些文件以指向优化的缩小文件。问题是我无法看到如何使用gulp来修改这些文件以指向优化文件以进行调试和发布,因为源文件需要是目标文件,并且该机制需要与TFS一起使用。我所拥有的最好的想法是使用捆绑机制。在投入时间之前,我想看看是否有更简单的替代方案。

2 个答案:

答案 0 :(得分:1)

这是我的解决方案,如果有更好的方法,请告诉我。 我跑了:

top_n

然后我修改了BundleConfig.cs以包含

 Install-Package System.Web.Optimization.HashCache

然后我修改了_Layout.cshtml以包含

var myBundle = new ScriptBundle("~/bundle_virtual_path").Include("~/Scripts/CombinedFile.js");
myBundle.Transforms.Add(new HashCacheTransform());
bundles.Add(myBundle);

通过这种方式,我使用bundle在gulp脚本的输出上执行缓存清除,该脚本可以附加到Task Runner Explorer中的before build事件。为了完整起见,这是一个非常简单的功能,可以在此示例中生成CombinedFile.js

 @{    
    if (HttpContext.Current.IsDebuggingEnabled)
    {
        <script src = "~/Scripts/App/File1.js" ></script>
        <script src = "~/Scripts/App/File2.js" ></script>
    }
     else
    {
         @Scripts.Render("~/bundle_virtual_path");
    }
 }

Gulp文件监听功能应附加到Project Open事件

答案 1 :(得分:1)

我找到了一个解决方案,但没有将.net捆绑到图片中。

使用gulp插件gulp-rev和名为FileTagger的nuget包

gulp.js

var gulp = require('gulp'),
     rimraf = require("rimraf"),
     concat = require("gulp-concat"),
     cssmin = require("gulp-cssmin"),
     uglify = require("gulp-uglify"),
     filter = require("gulp-filter"),
     rename = require("gulp-rename"),
     rev = require('gulp-rev');

var paths = {};
paths.jsSource = mainBowerFiles();
paths.baseReleaseFolder = "app";
///these names get alter by rev()
paths.baseJSReleaseFile = "site.min.js";

gulp.task("min:js", function () {
var jsFilter = filter('**/*.js', { restore: true });
return gulp
    .src(paths.jsSource)
    .pipe(jsFilter)
    .pipe(uglify())
    .pipe(concat(paths.baseReleaseFolder + "/" + paths.baseJSReleaseFile))
    .pipe(rev())
    .pipe(gulp.dest("."))
    .pipe(jsFilter.restore);
});

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>App</title>   
@FileTagger.Render.Script("~/app/site-*.min.js")
</head>
    <body>@RenderBody()</body>
</html>