本文将介绍使用的打包和压缩的优点,以及如何在 ASP.NET Core 应用程序中使用这些功能。
在 ASP.Net 中可以使用打包与压缩这两种技术来提高 web 应用程序页面加载的性能。通过减少从服务器请求的次数和减少资源文件的体积来提高加载性能。
例如下面 JavaScript 函数:
- AddAltToImg = function (imageTagAndImageID, imageContext) {
- ///<signature>
- ///<summary> Adds an alt tab to the image
- // </summary>
- //<param name="imgElement" type="String">The image selector.</param>
- //<param name="ContextForImage" type="String">The image context.</param>
- ///</signature>
- var imageElement = $(imageTagAndImageID, imageContext);
- imageElement.attr('alt', imageElement.attr('id').replace(/ID/, ''));
- }
压缩后,函数简化为如下:
- AddAltToImg = function(t, a) {
- var r = $(t, a);
- r.attr("alt", r.attr("id").replace(/ID/, ""))
- };
除了删除注释和不必要的空格之外,参数和变量名称被重命名(缩写)如下:
原始名称 | 重命名后 |
---|---|
imageTagAndImageID | t |
imageContext | a |
imageElement | r |
此示例来自于 github:https://github.com/aspnet/Docs/blob/master/aspnetcore/client-side/bundling-and-minification.md
MVC 项目模板提供了一个
配置文件,它定义了打包的配置选项。默认情况下,实现了自定义脚本文件 (wwwroot/js/site.js) 和样式表 (wwwroot/css/site.css) 文件的配置。
- bundleconfig.json
- [
- {
- "outputFileName": "wwwroot/css/site.min.css",
- "inputFiles": [
- "wwwroot/css/site.css"
- ]
- },
- {
- "outputFileName": "wwwroot/js/site.min.js",
- "inputFiles": [
- "wwwroot/js/site.js"
- ],
- "minify": {
- "enabled": true,
- "renameLocals": true
- },
- "sourceMap": false
- }
- ]
配置选项详细说明:
文件的相对路径。必填
- bundleconfig.json
- minify: { enabled: true }
在 VS 2015/2017 需要安装 BundlerMinifierVsix,安装完成后需要重启 VS。
在
文件右键单击,然后选择任务运行程序资源管理器。
- bundleconfig.json
在
选项右键单击,然后选择 Run。
- Update all fiels
在项目中会分别生成压缩后的资源文件。
在上一篇博客《ASP.NET Core 配置环境变量和启动设置》我们已经讨论过环境变量,在视图中通过 Environment 标签,分别定义开发、预演和生产环境加载对应的资源文件。
- <environment names="Development">
- <link rel="stylesheet" href="~/css/site.css" />
- <script src="~/js/site.js" asp-append-version="true">
- </script>
- </environment>
- <environment names="Staging,Production">
- <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true"
- />
- <script src="~/js/site.min.js" asp-append-version="true">
- </script>
- </environment>
当在开发模式下运行应用程序,我们使用未压缩 Css 和脚本文件;在生产环境中,我们压缩后的资源文件,这样可以提高应用程序的性能。
在 ASP.Net 中可以使用打包与压缩这两种技术来提高 Web 应用程序页面加载的性能。希望上面的内容对大家的学习有所帮助,谢谢!
参考:
第一次使用 Markdown 写博客,还不是很习惯,排版不够整齐,请大家见谅,谢谢!
来源: http://www.cnblogs.com/tdfblog/p/bundling-and-minification-in-asp-net-core.html