我有几个想要实现的目标,但我不确定如何实现:
- 为我的 Web 项目创建一个单击部署,其中包含一个缩小的 javascript 文件
- 对我缩小的 JavaScript 文件进行版本控制,以防止在推送新版本时浏览器缓存静态内容
- 在 RELEASE 构建中引用版本化的 JavaScript 文件,在 DEBUG 构建中引用非压缩版本的 JavaScript 文件
来自这篇文章:
http://encosia.com/automatically-minify-and-combine-javascript-in-visual-studio/
我添加了 JSMin 以使用如下命令缩小我的文件:
"$(SolutionDir)Tools\jsmin.exe" < "$(ProjectDir)Scripts\myfile.js" > "$(ProjectDir)Scripts\myfile.min.js"
我还将把它添加到我的网页中,以便在 Debug模式下保留非缩小文件:
<% if (HttpContext.Current.IsDebuggingEnabled) { %>
<script type="text/javascript" src="scripts\myfile.js"></script>
<% } else { %>
<script type="text/javascript" src="scripts/myfile.min.js"></script>
<% } %>
所以实际上我只剩下试图弄清楚如何防止 myfile.min.js 在更新时被 Web 浏览器视为静态内容。如果我的目标不是单击部署,我可以手动添加一个版本号,但这似乎不是一个可靠的方法。想法?
最佳答案
这个答案有点晚了,但我认为这是一种相当可靠的方法,可以根据文件本身的校验和确保缓存行为与文件同步。
<script type="text/javascript" src="/Scripts/Scripts.min.js?v=<%= Utils.GetFileHash("/Scripts/Scripts.min.js") %>"></script>
在你的 Utils 类中,你有生成文件校验和的方法
public static string GetFileHash(string path)
{
string hash = (string)HttpContext.Current.Cache["_hash_" + path];
if (hash == null)
{
// Get the physical path of the file
string file = HttpContext.Current.Server.MapPath(path);
// Code for MD5 hashing omitted for brevity
hash = Utils.GetMD5(file);
// Insert the hash into the Cache, with a dependency on the underlying file
HttpContext.Current.Cache.Insert("_hash_" + path, hash, new System.Web.Caching.CacheDependency(file));
}
return hash;
}
这会缓存文件的哈希值,因此只需在文件更改时计算它。
此外,CacheDependency 确保如果您要更改 .js 文件,它会确保重新生成哈希。
希望这对您有所帮助,这是我在我的一个生产网站中使用的内容。
关于javascript - 使用 VS2010 缩小 JavaScript 并附加版本号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7688149/