繁体   English   中英

针对不同环境更新 HTML 页面中的 JS 引用

[英]Update JS references in HTML page for different environments

我有两种类型的生成 JS 文件:

  1. xyz.js
  2. xyz.min.js

我想在不同的时间、针对不同的环境参考这两者。

目前我需要手动更新引用,因为有大量的 JS 文件:是否有任何技术可以避免手动更新。 这可能吗?

使用 GruntJS,你有多种选择来解决这个问题:

1.指向 html 中的一个文件,并根据环境切换编译到不同文件夹的版本/类型(可能至少有两个 Grunt-Tasks):

grunt build:devgrunt build:live


2.使用grunt-processhtml包。 您可以再次根据您的环境需要不同的目标 像这样的东西(未经测试):

``

<!-- build:dev -->
<script src="js/lib/path/lib.js"></script>
<script src="js/deep/development/path/script.js"></script>
<!-- /build -->

<!-- build:dist -->
<script src="js/app.min.js"></script>
<!-- /build -->

``

还有grunt-targethtmlgrunt-preprocessgrunt-htmlrefs


3.或者只让它在为分发环境构建时将 src 更改为.min

``

<!-- build:dist:js js/app.min.js -->
<script src="js/app.js"></script>
<!-- /build -->

<!-- changed to -->
<script src="js/app.min.js"></script>

``


4.假设您使用grunt-uglify您只能再次指向一个文件,然后让 grunt-uglify 也生成source-maps 有了这些,您可以为所有环境提供缩小版本,但旁边还有一个 sourceMapping 文件,当您在控制台/调试器中查看代码时,它看起来像 development-code: Introduction to JavaScript Source Maps


5.阅读Addy Osmani一篇关于此文章,他还指出了字符串/正则表达式替换(摘自他的文章):

    'string-replace': {
      prod: {
        src: './app/**/*.html',
        dest: './dist/',
        options: {
          replacements: [{
            pattern: 'source.js',
            replacement: 'build.js'
          }]
        }
      }

6.他还提到,您可以在 HTML 中使用模板变量,让grunt-templategrunt-include-replace为您完成工作。

使用第三方解决方案不是一个好主意。 使用 helper 类来包含 js 和 css 文件。 您也可以为您的文件添加 vesioning(如果您的 js 更改,用户不需要清除缓存)。

在 _Layout.cshtml 中:

@Html.IncludeJs("~/js/grid.js")

IncludeJs 扩展方法的来源:

public static class JavascriptExtension
{
    public static MvcHtmlString IncludeJs(this HtmlHelper helper, string filename)
    {
        if (ConfigurationManager.AppSettings.Get("minimizeJs") == "true")
        {
            filename = Regex.Replace(filename, "\.js$", ".min.js");
        }
        string version = GetVersion(helper, filename);
        return MvcHtmlString.Create("<script src='" + VirtualPathUtility.ToAbsolute(filename) + version + "'></script>");
    }

    private static string GetVersion(this HtmlHelper helper, string filename)
    {
        var context = helper.ViewContext.RequestContext.HttpContext;

        if (context.Cache[filename] == null)
        {
            var physicalPath = context.Server.MapPath(filename);
            var version = "?v=" + new System.IO.FileInfo(physicalPath).LastWriteTime.ToString("yyyyMMddhhmmss");
            context.Cache.Add(physicalPath, version, null, DateTime.Now.AddMinutes(1), TimeSpan.Zero, CacheItemPriority.Normal, null);
            context.Cache[filename] = version;
            return version;
        }
        else
        {
            return context.Cache[filename] as string;
        }
    }

}

暂无
暂无

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

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