Minify .cshtml files with gulp
Minification is just one of the ways you can make your website more accessible to others, besides other options like adding a load balancer to help distribute network traffic or upgrading to the latest and greatest version of your framework (which you SHOULD do if you are using .NET Core). Thankfully, minification is easy and this library aims to give you the biggest possible performance improvement for your .cshtml/html files.
Why not use another minification library that's recommended by Google? That library only works on HTML files, but rest assured, we are taking heavy inspiration from this library in order to make use of the same minification techniques for .cshtml files. In case our library's approach of using gulp to minify your .cshtml does not work for you, I would recommend an .exe in order to minify your .cshtml and steer you away from options like this if you can help it. (Minifying at runtime incurs a performance penalty).
- [X] Removes leading/trailing whitespace
- [X] Removes HTML/Razor/CSS comments
- [X] Minifies inline blocks with uglify-js
- [X] Minifies inline blocks with clean-css
- [X] Remove optional closing tags
- [X] Collapse whitespace within tag attributes
- [X] Remove quotes around eligible tag attribute values
- [X] Remove optional closing slashes on void elements
- [X] Remove url schemes
npm install gulp-cshtml-minify
var minifyCshtml = require('gulp-cshtml-minify'),
gulp = require('gulp');gulp.src("test.cshtml")
.pipe(minifyCshtml())
.pipe(gulp.dest("result"));
`Options
You can pass in a number of options into the function to customize what options are turned on and off. The values shown below are the default options and will be set as such if you do not pass in any custom options when running the library (as seen in the above example).
`
var minifyCshtml = require('gulp-cshtml-minify'),
gulp = require('gulp');gulp.src("test.cshtml")
.pipe(minifyCshtml({
removeHtmlComments: true,
removeRazorComments: true,
removeCssComments: true,
minifyCss: true,
minifyJs: true,
collapseWhitespace: false, / collapses whitespace to one space /
optionalClosingTags: true, / removes optional tags /
urlSchemes: true, / https:// -> // /
uglifyjsOptions: {}, / options for uglifyjs /
cleancssOptions: {} / options for cleancss /
}))
.pipe(gulp.dest("result"));
``Note - Collapsing whitespace can cause issues if you are relying on spacing to display inline elements.
Note - Removing optional closing tags in seldom circumstances may lead to unexpected behavior.
Note - Shortening the url schemes may cause problems if you load resources over https when your page is loaded over http, which should no longer apply to the majority (but may apply to you).
| Url | Original | Minified | Savings |
| ------------- |-------------| ----- | ----- |
| MDN | 112.9KB | 97KB | 15%
| Vox | 157.5KB | 138KB | 12.4%
| Food Network | 151.8KB | 126.2KB | 17%
| Olive Garden | 620.1KB | 536.9KB | 14%