[英]Update JS references in HTML page for different environments
我有兩種類型的生成 JS 文件:
我想在不同的時間、針對不同的環境參考這兩者。
目前我需要手動更新引用,因為有大量的 JS 文件:是否有任何技術可以避免手動更新。 這可能嗎?
使用 GruntJS,你有多種選擇來解決這個問題:
1.指向 html 中的一個文件,並根據環境切換編譯到不同文件夾的版本/類型(可能至少有兩個 Grunt-Tasks):
grunt build:dev
和grunt 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-targethtml或grunt-preprocess或grunt-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-template
或grunt-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.