<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Gulp &#8211; Cognim &#8211; Internet development</title>
	<atom:link href="https://www.cognim.co.uk/category/gulp/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.cognim.co.uk</link>
	<description>Enterprise system implementation. Making the complex simple</description>
	<lastBuildDate>Tue, 10 Nov 2015 10:10:24 +0000</lastBuildDate>
	<language>en-GB</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
<site xmlns="com-wordpress:feed-additions:1">91553907</site>	<item>
		<title>Gulp and Visual Studio: Code quality</title>
		<link>https://www.cognim.co.uk/gulp-and-visual-studio-code-quality/</link>
					<comments>https://www.cognim.co.uk/gulp-and-visual-studio-code-quality/#respond</comments>
		
		<dc:creator><![CDATA[Darren Hall]]></dc:creator>
		<pubDate>Tue, 10 Nov 2015 09:58:30 +0000</pubDate>
				<category><![CDATA[Gulp]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<guid isPermaLink="false">http://www.cognim.co.uk/?p=5258</guid>

					<description><![CDATA[This is Part 4 is my series on using Gulp with Visual Studio. So far we&#8217;ve covered setting up Visual Studio for use with Gulp, processing SASS, and getting the files ready for deployment. Part 1: Setting up Gulp with Visual Studio Part 2: Getting SASSy Part 3: Deployment: minification and concatenation Part 4: Code [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>This is Part 4 is my series on using Gulp with Visual Studio. So far we&#8217;ve covered setting up Visual Studio for use with Gulp, processing SASS, and getting the files ready for deployment.</p>
<ul>
<li><a href="https://www.cognim.co.uk/getting-started-with-gulp-and-vs/" target="_blank">Part 1: Setting up Gulp with Visual Studio</a></li>
<li><a href="https://www.cognim.co.uk/gulp-and-visual-studio-sass/">Part 2: Getting SASSy</a></li>
<li><a href="https://www.cognim.co.uk/gulp-vs-minification/">Part 3: Deployment: minification and concatenation</a></li>
<li>Part 4: Code quality: tests and linting</li>
<li>Part 5: Thoughts on Gulp</li>
</ul>
<p>In this post I want to talk about JavaScript code quality.</p>
<h3>Code quality: tests and linting</h3>
<p>JavaScript is a notoriously quirky language &#8211;  the tricky &#8220;this&#8221; operator, lack of block level scoping, the ability to use variables before declaring them, &#8220;==&#8221; vs &#8220;===&#8221;, etc etc.</p>
<p>We can do a number of things to tighten up our code quality. We can run tests to ensure our code works as expected, and we can run a linting program to catch any syntatic mistakes before running our code. Combining this with Gulp gives a nice workflow for development.</p>
<h4>Linting with JSHint</h4>
<p><a href="http://stackoverflow.com/questions/8503559/what-is-linting" target="_blank">Linting</a> is a process of running a program to analyse code for potential problems, catching bugs before the program gets executed. Douglas Crockford created <a href="http://www.jslint.com/" target="_blank">JSLint</a> in 2011, and of course there is a <a href="https://www.npmjs.com/package/gulp-jslint" target="_blank">gulp plugin</a> for it. However, I prefer to use <a href="http://jshint.com/" target="_blank">JSHint</a> &#8211; a community offshoot of JSLint that allows for more customisation and is slightly more relaxed in its defaults. You can find a good comparison of the two <a href="http://stackoverflow.com/a/10763615" target="_blank">here</a>.</p>
<p>First, I would seperate out any third-party libraries or frameworks you have into their own folder(s). In my opinion this is good practice anyway, but especially if we are running linting &#8211; we don&#8217;t want failures on code we haven&#8217;t written! Next, we want to add the <a href="https://www.npmjs.com/package/gulp-jshint" target="_blank">plugin</a> to our package.json:</p>
<pre class="lang:js decode:true ">{
  "scripts": { "install": "echo Done" },
    
  "devDependencies": {
    "gulp": "~3.9.0",
    "gulp-load-plugins": "~0.10.0",
    "gulp-jshint": "~1.11.2",
    // other plugins here
  } 
}</pre>
<p>Then, add the Gulp task to our gulpfile:</p>
<pre class="lang:c# decode:true" title="gulpfile.js">var sources = ['./Scripts/*.js', '!./Scripts/libs/*.js'];

gulp.task('watch-lint', function () {
    gulp.watch(sources, ['lint']);
});

gulp.task('lint', function () {
    return gulp.src(sources)
        .pipe(plugins.jshint({
            strict: true,
            predef: [""]
        }))
        .pipe(plugins.jshint.reporter('default'))
        .pipe(plugins.jshint.reporter('fail'))
    ;
});</pre>
<p>Here&#8217;s a line by line breakdown of the important stuff:</p>
<ul>
<li>Line 1: Define the JavaScript files we want linting, excluding any third party libraries and frameworks</li>
<li>Line 3-5: Set up a watch to run the linting task whenever we make a change to our JavaScript</li>
<li>Line 7: Set up our linting task</li>
<li>Line 8-12: Send our files to JSHint. JSHint has a number of options you can set to define how lenient or strict you want it to be. You can look at the <a href="http://jshint.com/docs/" target="_blank">docs</a> to get an idea of what you can set. Here I&#8217;m only using the strict option (<a href="http://www.nczonline.net/blog/2012/03/13/its-time-to-start-using-javascript-strict-mode/" target="_blank">here</a> is a good blog explaining strict mode). There is also a section to define any global variables you&#8217;re using that should be ignored &#8211; for example if you&#8217;re using Angular you&#8217;ll want to add &#8220;angular&#8221; here</li>
<li>Line 13-14: Send the output of the linting to some inbuilt reporters &#8211; one to output the results to console and one to raise an error for any failures</li>
</ul>
<p>Now we can add the watch task to our default task, and we&#8217;ll have linting every time we change our code.</p>
<h4>Tests with Karma</h4>
<p>One of the great things about Gulp is that you can get a Gulp task to run other Node based packages directly. For example, you can run <a href="http://karma-runner.github.io" target="_blank">Karma</a> within a task, without having to use a plugin. Combined with <a href="http://phantomjs.org/" target="_blank">PhantomJS</a>, a headless browser, you get a great unit testing framework for your JavaScript. First, add the packages:</p>
<pre class="lang:c# decode:true " title="package.json">{
  "scripts": { "install": "echo Done" },
    
  "devDependencies": {
    "gulp": "~3.9.0",
    "karma-jasmine": "~0.3.6",
    "karma": "~0.13.9",
    "karma-phantomjs-launcher": "~0.2.1"
    // other plugins here
  } 
}</pre>
<p>Then, we&#8217;ll need to add our karma config file (karma.conf.js) at the root of the project :</p>
<pre class="lang:js decode:true" title="karma.conf.js">module.exports = function (config) {
    config.set({
        files: ['./Scripts/*.js',
                './Scripts/Specs/**/*.js',
        ],

        exclude: ['./Scripts/libs/*.js'],

        frameworks: ['jasmine'],

        autoWatchBatchDelay: 1000,

        reporters: ['progress'],

        browsers: ['PhantomJS']
    });
};</pre>
<p>One thing I&#8217;ve found using Karma in Visual Studio: often Karma can crash in Visual Studio with an &#8220;EBUSY&#8221; error. I haven&#8217;t found an adequate explanation for this yet &#8211; I think it&#8217;s because when you modify and save a file Visual Studio writes a temporary file to replace the file you are saving, which doesn&#8217;t sit well with Node. This can be mitigated by setting the &#8220;autoWatchBatchDelay&#8221; to 1000, which waits 1 second after any change before running tests.</p>
<p>Finally, our gulp task:</p>
<pre class="lang:js decode:true">var Server = require('karma').Server;

gulp.task('runTests', function () {
    new Server({
        configFile: __dirname + '/karma.conf.js',
        singleRun: false
    }).start();
});</pre>
<p>Here, we are simply firing up Karma from within a Gulp task and passing in our karma config file. We are also telling Karma to watch our files for any changes and re-run our tests if they change. If you are going to run this task on a build server (and you should), you&#8217;ll need to configure the singleRun variable here. This can be done by using <a href="https://www.npmjs.com/package/yargs" target="_blank">yargs</a> to pass in a variable to switch this behaviour.</p>
<p>There we are! There is a commit of all the changes <a href="https://github.com/edwardridge/Gulp-and-Visual-Studio/commit/92ba6c092e262261171c642aa765129238e00283">here</a>, which includes a sample test. I highly recommend using both linting and unit tests when writing JavaScript code, and Gulp is great at running these tasks for us.</p>
<p>Next, in the last past I want to share my thoughts on Gulp, specifically within the .NET ecosystem.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.cognim.co.uk/gulp-and-visual-studio-code-quality/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5258</post-id>	</item>
		<item>
		<title>Gulp and Visual Studio: concatenation and minification</title>
		<link>https://www.cognim.co.uk/gulp-vs-minification/</link>
					<comments>https://www.cognim.co.uk/gulp-vs-minification/#comments</comments>
		
		<dc:creator><![CDATA[Darren Hall]]></dc:creator>
		<pubDate>Thu, 24 Sep 2015 15:04:44 +0000</pubDate>
				<category><![CDATA[Gulp]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<guid isPermaLink="false">http://www.cognim.co.uk/?p=5268</guid>

					<description><![CDATA[In my previous blog I wrote about how we can use Gulp to compile SASS. This time it&#8217;s all about how we can use Gulp in Visual Studio to prepare files for a release by minifying and concatenating them. I&#8217;ve put up a project using the standard MVC 5 template for this series of posts [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In my previous blog I wrote about how we can use Gulp to compile SASS. This time it&#8217;s all about how we can use Gulp in Visual Studio to prepare files for a release by minifying and concatenating them. I&#8217;ve put up a project using the standard MVC 5 template for this series of posts <a href="https://github.com/edwardridge/Gulp-and-Visual-Studio" target="_blank">here</a></p>
<ul>
<li><a href="https://www.cognim.co.uk/getting-started-with-gulp-and-vs/" target="_blank">Part 1: Setting up Gulp with Visual Studio</a></li>
<li><span style="color: #000000;"><a href="https://www.cognim.co.uk/gulp-and-visual-studio-sass/" target="_blank">Part 2: Getting SASSy</a></span></li>
<li><span style="color: #999999;"><a href="https://www.cognim.co.uk/gulp-vs-minification">Part 3: Deployment: minification and concatenation</a></span></li>
<li><span style="color: #999999;">Part 4: Code quality: tests and linting</span></li>
<li><span style="color: #999999;">Part 5: Thoughts on Gulp</span></li>
</ul>
<h3>Small is beautiful</h3>
<p>To increase the speed of a site, and to save bandwidth, we want to:</p>
<ul>
<li>Have as few requests for the smallest files possible</li>
<li>Cache these files for as long as possible</li>
</ul>
<p>We can achieve this by concatenating and minifying the files, then adding a hash of the files contents to the filename so they can be cached indefinitely.</p>
<p>There are a number of different ways of approaching minification and concatenation with Gulp, and a lot of different plugins and plugin combinations. The following is a style that has worked for me, you may need to adjust it to suit your own workflow.</p>
<h3>Plugins</h3>
<p>There are a number of plugins we will need:</p>
<ul>
<li><a href="https://www.npmjs.com/package/gulp-useref">gulp-useref</a> for concatenation</li>
<li><a href="https://www.npmjs.com/package/gulp-uglify">gulp-uglify</a> and <a href="https://www.npmjs.com/package/gulp-minify-css">gulp-minify-css</a> for minifcation of JavaScript and CSS respectively</li>
<li><a href="https://github.com/sindresorhus/gulp-rev">gulp-rev</a> and <a href="https://github.com/jamesknelson/gulp-rev-replace">gulp-rev-replace</a> for revisioning</li>
<li><a href="https://www.npmjs.com/package/gulp-filter">gulp-filter</a> for filtering files to process them independently</li>
</ul>
<p>Lets add these to the package.json:</p>
<pre class="lang:js decode:true">{
  "scripts": { "install": "echo Done" },
    
  "devDependencies": {
    "gulp": "~3.9.0",
    "gulp-load-plugins": "~0.10.0",
    "gulp-useref": "~1.3.0",
    "gulp-uglify": "~1.2.0",
    "gulp-minify-css": "~1.2.1",
    "gulp-rev": "~5.1.0",
    "gulp-rev-replace": "~0.4.2",
    "gulp-filter": "~3.0.0"
  } 
}
</pre>
<h3>Referencing scripts and CSS</h3>
<p>Now we&#8217;ll want to add our CSS and JavaScript files to our pages. These are put in commented <strong>build blocks</strong> that let gulp-useref know where a section it should concatenate is. So, at the top of the page (here it&#8217;s the _Layout.cshtml page) we reference the CSS:</p>
<pre class="lang:xhtml decode:true">&lt;!-- build:css /dist/site.css --&gt;
    &lt;link href="/Content/bootstrap.css" rel="stylesheet" /&gt;
    &lt;link href="/Content/Site.css" rel="stylesheet" /&gt;
&lt;!-- endbuild --&gt;    
<!-- endbuild --></pre>
<p>In the first comment, we define two things:</p>
<ul>
<li>The first part, &#8220;build:css&#8221; tells useref that this be a CSS block</li>
<li>The second is the location of the concatenated file that will eventually be referenced (more on this later)</li>
</ul>
<p>We do the same at the bottom with the JavaScript:</p>
<pre class="lang:xhtml decode:true">&lt;!-- build:js /dist/libs.js --&gt;
    &lt;script src="/Scripts/Libraries/jquery.js"&gt;&lt;/script&gt;
    &lt;script src="/Scripts/Libraries/bootstrap.js"&gt;&lt;/script&gt;
    &lt;script src="/Scripts/Libraries/respond.js"&gt;&lt;/script&gt;
&lt;!-- endbuild --&gt;<script src="/Scripts/Libraries/respond.js"></script><!-- endbuild --></pre>
<p>We can have multiple build blocks of the same type (e.g. multiple JavaScript blocks) so we can have one for libraries (Angular, jQuery etc) which will change less frequently than the code we write.</p>
<h3>The Gulp task</h3>
<p>Now for the biggie &#8211; the actual task itself. I&#8217;ll put it here and go through it in more detail below:</p>
<pre class="nums:true lang:js decode:true">gulp.task('minifyFilesForRelease', function () {

    var cssFilter = plugins.filter('**/*.css', { restore: true });
    var jsFilter = plugins.filter('**/*.js', { restore: true });

    var assets = plugins.useref.assets();
    gulp.src('./**/*.cshtml')
        .pipe(assets)

        //Process JavaScript
        .pipe(jsFilter)
        .pipe(plugins.uglify())
        .pipe(plugins.rev())
        .pipe(assets.restore())
        .pipe(jsFilter.restore)
        
        //Process CSS
        .pipe(cssFilter)
        .pipe(plugins.minifyCss({
            keepSpecialComments: 0
        }))
        .pipe(plugins.rev())
        .pipe(assets.restore())
        .pipe(cssFilter.restore)

        .pipe(plugins.useref())
        .pipe(plugins.revReplace({
            replaceInExtensions: ['.js', '.css', '.html', '.cshtml']
        }))
        .pipe(gulp.dest(function (data) {
            return data.base;
        }
        ));
});</pre>
<p>Here&#8217;s a line by line breakdown of what&#8217;s happening:</p>
<ul>
<li>Line 1: Define the task</li>
<li>Line 3-4: Setup some filters we will use later to separate out the CSS and JavaScript for individual processing</li>
<li>Line 6: Reference the assets object of useref which will return the build blocks we setup earlier</li>
<li>Line 7: Get all our cshtml files</li>
<li>Line 8: Get all our build blocks in these files</li>
<li>Line 11: Filter our build blocks to just the JavaScript</li>
<li>Line 12: Minify the JavaScript</li>
<li>Line 13: Revision the JavaScript</li>
<li>Line 14-15: Remove the filters, so we have access to all our build blocks again</li>
<li>Line 18: Filter our build blocks to just the CSS</li>
<li>Line 19-21: Minify the CSS removing any and all comments</li>
<li>Line 22: Revision CSS</li>
<li>Line 23-24: Remove the filters again</li>
<li>Line 26: Replace the commented, unprocessed build block in our cshtml files with the processed ones</li>
<li>Line 27-29: Add the revision number to the processed files (note we need to include cshtml files here)</li>
<li>Line 30-32: Replace the original cshtml files. We need to specify a destination here, and as we have views in multiple  folders we can use <a href="http://stackoverflow.com/a/29437418">this technique by </a><a href="http://stackoverflow.com/users/1212682/yiling">Yiling</a> to overwrite a file regardless of its location</li>
</ul>
<p>Phew, there&#8217;s a lot there! If you run this task each build block in our cshtml files will be replaced with a single, minified, revisioned file.</p>
<p>Before:</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-1.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="alignnone size-large wp-image-5287" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-1.png?resize=1024%2C574&#038;ssl=1" alt="gulp-concat-1" width="1024" height="574" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-1.png?resize=1024%2C574&amp;ssl=1 1024w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-1.png?resize=300%2C168&amp;ssl=1 300w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-1.png?w=1197&amp;ssl=1 1197w" sizes="auto, (max-width: 1000px) 100vw, 1000px" /></a></p>
<p>After:</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-2.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="alignnone size-large wp-image-5286" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-2.png?resize=1024%2C575&#038;ssl=1" alt="gulp-concat-2" width="1024" height="575" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-2.png?resize=1024%2C575&amp;ssl=1 1024w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-2.png?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-2.png?w=1200&amp;ssl=1 1200w" sizes="auto, (max-width: 1000px) 100vw, 1000px" /></a></p>
<h3>Running in Release mode</h3>
<p>We only want to run this task when we&#8217;re putting together a release, whether that&#8217;s manual or (much better!) <a href="https://www.cognim.co.uk/know-exactly-what-youve-released-with-git-teamcity-and-octopus/">automated</a>. To do this, add a PreBuildEvent that runs the Gulp task before a release build. Go to the project properties, then Build Events and add the following to &#8220;Pre-build event command line&#8221;:</p>
<pre class="lang:default decode:true ">if $(ConfigurationName) == Release (
   cd $(ProjectDir)
   npm install
   gulp minifyFilesForRelease
)</pre>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-4.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="size-large wp-image-5284 aligncenter" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-4.png?resize=1024%2C571&#038;ssl=1" alt="gulp-concat-4" width="1024" height="571" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-4.png?resize=1024%2C571&amp;ssl=1 1024w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-4.png?resize=300%2C167&amp;ssl=1 300w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-4.png?w=1136&amp;ssl=1 1136w" sizes="auto, (max-width: 1000px) 100vw, 1000px" /></a></p>
<p>This will then run our minifying task only on a Release build.</p>
<p>Lastly, as we are adding the minified files to a &#8220;dist&#8221; folder that doesn&#8217;t exist during development, we&#8217;ll need to add this folder after each build. Open up the csproj for the web project, and at the very end add the following:</p>
<pre class="lang:c# decode:true">&lt;Target Name="AfterBuild"&gt;
    &lt;ItemGroup&gt;
      &lt;Content Include="dist\*.*" /&gt;
    &lt;/ItemGroup&gt;
 &lt;/Target&gt;</pre>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-3.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="size-large wp-image-5285 aligncenter" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-3.png?resize=1024%2C564&#038;ssl=1" alt="gulp-concat-3" width="1024" height="564" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-3.png?resize=1024%2C564&amp;ssl=1 1024w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-3.png?resize=300%2C165&amp;ssl=1 300w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/09/gulp-concat-3.png?w=1136&amp;ssl=1 1136w" sizes="auto, (max-width: 1000px) 100vw, 1000px" /></a></p>
<p>This will include the contents of our dist folder after each build.</p>
<h3>Wrapping up</h3>
<p>We now have an automated process for minifying and concenating files that doesn&#8217;t intefere with the development process. The commit for everything is <a href="https://github.com/edwardridge/Gulp-and-Visual-Studio/commit/a2a5eb8b4df4457db3c1025d2fb7162d39f0c1af" target="_blank">here</a>.</p>
<p>Happy Gulping!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.cognim.co.uk/gulp-vs-minification/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5268</post-id>	</item>
		<item>
		<title>Gulp and Visual Studio: Getting SASSy</title>
		<link>https://www.cognim.co.uk/gulp-and-visual-studio-sass/</link>
					<comments>https://www.cognim.co.uk/gulp-and-visual-studio-sass/#comments</comments>
		
		<dc:creator><![CDATA[Darren Hall]]></dc:creator>
		<pubDate>Fri, 04 Sep 2015 08:41:10 +0000</pubDate>
				<category><![CDATA[Gulp]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<guid isPermaLink="false">http://www.cognim.co.uk/?p=5230</guid>

					<description><![CDATA[Getting SASSy with Gulp in Visual Studio In my previous blog I showed you how to set up Visual Studio for use with Gulp. Now I want to show you how you can use it in everyday development, including processing SASS, running tests, linting your code and getting ready for deployment. In this series of [&#8230;]]]></description>
										<content:encoded><![CDATA[<h3>Getting SASSy with Gulp in Visual Studio</h3>
<p>In my <a href="https://www.cognim.co.uk/getting-started-with-gulp-and-vs/" target="_blank">previous blog</a> I showed you how to set up Visual Studio for use with Gulp. Now I want to show you how you can use it in everyday development, including processing SASS, running tests, linting your code and getting ready for deployment.</p>
<p>In this series of posts I&#8217;ll talk about how you can use Gulp with Visual Studio to run your common front end tasks:</p>
<ul>
<li><a href="https://www.cognim.co.uk/getting-started-with-gulp-and-vs/" target="_blank">Part 1: Setting up Gulp with Visual Studio</a></li>
<li><span style="color: #000000;"><a href="https://www.cognim.co.uk/gulp-and-visual-studio-sass/" target="_blank">Part 2: Getting SASSy</a></span></li>
<li><span style="color: #999999;">Part 3: Deployment: minification and concatenation</span></li>
<li><span style="color: #999999;">Part 4: Code quality: tests and linting</span></li>
<li><span style="color: #999999;">Part 5: Thoughts on Gulp</span></li>
</ul>
<p>The code I&#8217;ll be showing is based off a standard MVC 5 project. If you want the code I&#8217;ve created a GitHub project for it <a href="https://github.com/edwardridge/Gulp-and-Visual-Studio/">here.</a></p>
<h3>Basic Gulpfile + package.json</h3>
<p>Throughout these examples I&#8217;ll be using <a href="https://www.npmjs.com/package/gulp-load-plugins" target="_blank">gulp-load-plugins</a> &#8211; an awesome meta-plugin that takes all your Gulp plugins from your package.json and attaches them to an object. At the start, the package.json file looks like this:</p>
<pre class="lang:js decode:true" title="package.json">{
  "scripts": {"install": "echo Done"},
    
  "devDependencies": {
    "gulp": "~3.9.0",
    "gulp-load-plugins": "~0.10.0"
  } 
}
</pre>
<p>N.B. I like outputting something to the console after installing packages as the default is to not output anything, which can be a little confusing!</p>
<p>The basic gulpfile looks like this:</p>
<pre class="lang:js decode:true">var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();

gulp.task('default', ['']);</pre>
<p>Now, any plugins we add to our package.json will immediately be available on the plugins object.</p>
<h3>Processing SASS</h3>
<p>I&#8217;m a big fan of <a href="http://sass-lang.com/" target="_blank">SASS</a> for developing CSS as it helps keep my CSS clean and <a href="https://en.wikipedia.org/wiki/Don't_repeat_yourself" target="_blank">DRY</a>. SASS files need processing, and Gulp can do this for you. As a bonus, we can add <a href="http://code.tutsplus.com/tutorials/source-maps-101--net-29173" target="_blank">sourcemaps</a> so that when we inspect the page in Firefox, Chrome or IE 11 we refer back to the original SASS rather than the processed CSS. As a double bonus, we can use <a href="http://livereload.com/" target="_blank">LiveReload</a> to reload the page and automatically see our changes whenever we make a change to the SASS (note with LiveReload on Windows you&#8217;ll need the <a href="https://chrome.google.com/webstore/detail/livereload/jnihajbhpnppcggbcgedagnkighmdlei?hl=en" target="_blank">Chrome extension</a> for the best experience).</p>
<p>First off, we add the SASS file. For this demo project, based on MVC 5, this is simple &#8211; rename the Site.css file to Site.scss. As SASS is a superset of CSS, all valid CSS is valid SASS.</p>
<p>Next, we add the plugins we&#8217;ll need to the package.json:</p>
<pre class="lang:js decode:true">{
  "scripts": { "install": "echo Done" },
    
  "devDependencies": {
    "gulp": "~3.9.0",
    "gulp-load-plugins": "~0.10.0",
    "gulp-sass": "~2.0.4",
    "gulp-sourcemaps": "~1.5.2",
    "gulp-autoprefixer": "~2.3.1",
    "gulp-livereload": "~3.8.0"
  } 
}</pre>
<p>Next, add the gulp tasks &#8211; one to process the SASS into CSS, and another to watch the SASS files and recompile whenever we make a change:</p>
<pre class="nums:true lang:js decode:true" title="gulpfile.js">var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();

gulp.task('sass', function () {
    gulp.src('./Content/*.scss')
        .pipe(plugins.sourcemaps.init())
        .pipe(plugins.sass())
        .pipe(plugins.autoprefixer())
        .pipe(plugins.sourcemaps.write())
        .pipe(gulp.dest('./Content'))
        .pipe(plugins.livereload())
    ;
});

gulp.task('watch-sass', function () {
    plugins.livereload.listen();
    gulp.watch('./Content/*.scss', ['sass']);
});

gulp.task('default', ['watch-sass']);</pre>
<p>Here&#8217;s a line by line breakdown of what is happening within our &#8216;sass&#8217; task:</p>
<ul>
<li>Line 5: Grab all our SASS files from the Content folder. At the moment this is just the Site.scss file, but as we build this up we&#8217;ll want to add different SASS files for different parts of the project</li>
<li>Line 6: Initialise the sourcemaps. Note that <strong>this must be done before they get processed</strong></li>
<li>Line 7: Process the SASS to generate the CSS</li>
<li>Line 8: Use <a href="https://github.com/postcss/autoprefixer" target="_blank">autoprefixer</a> to add any vendor-specific prefixes to the CSS. The defaults for the <a href="https://www.npmjs.com/package/gulp-autoprefixer" target="_blank">plugin</a> target any browser with &gt;1% share, which is eminently sensible</li>
<li>Line 9: Insert the sourcemaps into the generated CSS</li>
<li>Line 10: Write the generated CSS back to the Content directory</li>
<li>Line 11: Notify LiveReload that we&#8217;ve made changes</li>
</ul>
<p>The &#8216;watch-sass&#8217; task simply tells LiveReload to start listening, watches our SASS files for any changes, and when they are changed runs our &#8216;sass&#8217; task. This watch has also been added to the default task, so will run automatically. Now, when we make a change to the Site.scss file the css will automatically get generated, and we get all the other goodness from our other plugins too.</p>
<h4>Sourcemaps</h4>
<p>Below I&#8217;ve changed the Site.scss file so that the text in the Jumbtron is blue, and have inspected it in Chrome. You&#8217;ll notice the red box in the inspector refers to the Site.scss file (not the generated Site.css file) , thanks to sourcemaps.</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-process-files-1.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="alignnone size-large wp-image-5242" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-process-files-1.png?resize=910%2C1024&#038;ssl=1" alt="gulp-process-files-1" width="910" height="1024" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-process-files-1.png?resize=910%2C1024&amp;ssl=1 910w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-process-files-1.png?resize=267%2C300&amp;ssl=1 267w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-process-files-1.png?w=960&amp;ssl=1 960w" sizes="auto, (max-width: 910px) 100vw, 910px" /></a></p>
<h4>LiveReload</h4>
<p>If you open the site in Chrome and start the LiveReload extension, any time a change is made to the SASS the web page will automatically reload with the changes. Here the color of the jumbotron text is switching between red and blue, and automatically updating:</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-live-reload.gif?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="alignnone size-full wp-image-5241" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-live-reload.gif?resize=800%2C378&#038;ssl=1" alt="gulp-live-reload" width="800" height="378" /></a></p>
<h3>Wrapping up</h3>
<p>So there we are! Automatic processing of SASS with Gulp, along with a few other goodies. The commit for eveything I&#8217;ve shown is <a href="https://github.com/edwardridge/Gulp-and-Visual-Studio/commit/8d00491f141298732887df2b87c36a569bc165de" target="_blank">here. </a></p>
<p>One thing to note is that in this task we didn&#8217;t do anything minification to the CSS &#8211; I&#8217;ll come on to that in my next post.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.cognim.co.uk/gulp-and-visual-studio-sass/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5230</post-id>	</item>
		<item>
		<title>Getting started with Gulp in Visual Studio 2013 and 2015</title>
		<link>https://www.cognim.co.uk/getting-started-with-gulp-and-vs/</link>
					<comments>https://www.cognim.co.uk/getting-started-with-gulp-and-vs/#comments</comments>
		
		<dc:creator><![CDATA[Darren Hall]]></dc:creator>
		<pubDate>Fri, 07 Aug 2015 09:56:50 +0000</pubDate>
				<category><![CDATA[Gulp]]></category>
		<category><![CDATA[Node]]></category>
		<category><![CDATA[NodeJs]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<guid isPermaLink="false">http://www.cognim.co.uk/?p=5148</guid>

					<description><![CDATA[In the last few years a rich set of front end development tools has emerged for building complex web applications. Gulp in particular has taken off in a huge way. However, .NET development is lagging when it comes to adoption of these tools. This is all set to change, especially with the release of ASP.NET 5 where Gulp will become [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In the last few years a rich set of front end development tools has emerged for building complex web applications. Gulp in particular has taken off in a huge way. However, .NET development is lagging when it comes to adoption of these tools. This is all set to change, especially with the release of ASP.NET 5 where Gulp will become part of the standard project setup. But, what is Gulp, and how do you use it in Visual Studio?</p>
<h2>What is Gulp?</h2>
<p><a href="http://gulpjs.com/">Gulp</a> is a build process for front end development. Gulp automates all of the repetitive tasks you have to do to prepare your front end files (such as JavaScript and CSS) for development and deployment. Gulp uses small, simple, composable plugins to that let you define exactly what happens to the files in your build.</p>
<h4>Common tasks you can get Gulp to automate</h4>
<ul>
<li>Minifying JavaScript/CSS/images</li>
<li>Concatenating JavaScipt/CSS files</li>
<li>Running JavaScript lint tooling</li>
<li>Compiling your SASS/LESS</li>
<li>Compiling TypeScript/CoffeeScript</li>
<li>Running JavaScript tests (eg Karma, Jasmine, Mocha)</li>
<li>Transpiling ES6 into ES5</li>
<li>Minifying Angular without breaking Dependency Injection</li>
<li>&#8230;and many more</li>
</ul>
<p>To install and use Gulp, you&#8217;ll need npm. Which begs the question&#8230;</p>
<h4>What is npm?</h4>
<p>npm is the package manager for [simple_tooltip content=&#8217;Node is a runtime environment built in JavaScript. It is somewhat equivalent to the .NET CLR &#8211; and for getting set up it is not necessary to know much more than that&#8217;]<span style="text-decoration: underline;">Node</span>[/simple_tooltip]. It&#8217;s a front-end equivalent to NuGet &#8211; you can use it to install and update packages and their dependencies. We&#8217;ll be using it to install Gulp and all its plugins.</p>
<h2>How to set up Gulp in Visual Studio</h2>
<p>Currently you can set up Gulp in Visual Studio 2013 and 2015. If you have 2015, skip the first 3 points as they come with Visual Studio 2015. Note that the screenshots are taken using Visual Studio 2013 with a standard MVC 5 project template.</p>
<ol>
<li>
<h4>Install Node/npm.</h4>
<p>You can install Node <a href="https://nodejs.org/" target="_blank">from here</a>. What we&#8217;re really after here isn&#8217;t Node, it&#8217;s npm (which comes installed with Node).</li>
<li>
<h4>Install Gulp.</h4>
<p>After installing npm, open up a Console window, and enter:</p>
<blockquote><p>npm install gulp -g</p></blockquote>
<p>This will install Gulp. The &#8220;-g&#8221; option installs it globally, so you can run Gulp commands anywhere.</li>
<li>
<h4>Install the Grunt Launcher Visual Studio Extension.</h4>
[simple_tooltip content=&#8217;Grunt is another build process for front end development. Grunt favours configuration, while Gulp favours code. I am not going to get into the merits of each here!&#8217;]<a href="https://visualstudiogallery.msdn.microsoft.com/dcbc5325-79ef-4b72-960e-0a51ee33a0ff" target="_blank">Grunt Launcher</a>[/simple_tooltip] provides menu options to install npm packages and run Gulp tasks from within Visual Studio.</li>
<li>
<h4>Add Gulp to your project</h4>
<p>At the root of your web project, add a new JSON file called package.json with the following contents:</p>
<pre class="lang:js decode:true">{
    "devDependencies": {
        "gulp":  "3.9.0"
    }   
}
</pre>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-1.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="  wp-image-5173 aligncenter" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-1.png?resize=889%2C420&#038;ssl=1" alt="gulp-blog-1" width="889" height="420" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-1.png?resize=1024%2C484&amp;ssl=1 1024w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-1.png?resize=300%2C142&amp;ssl=1 300w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-1.png?w=1379&amp;ssl=1 1379w" sizes="auto, (max-width: 889px) 100vw, 889px" /></a> The [simple_tooltip content=&#8217;Note a standard package.json will contain other information such as a description, author and a repository for the code&#8217;]<span style="text-decoration: underline;">package.json</span>[/simple_tooltip] is a npm file we use to define metadata about our project. Here we are listing the (front end) dependencies for developing our project &#8211; this will include plugins for running Gulp tasks. For now, we just want to add Gulp to our project.</p>
<p>Now, right-click on the package.json file and click &#8220;NPM install packages&#8221; (if you&#8217;ve installed Grunt Launcher) to add it to our project.</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/NPM-install-vid.gif?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class=" size-full wp-image-5171 aligncenter" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/NPM-install-vid.gif?resize=784%2C600&#038;ssl=1" alt="NPM install vid" width="784" height="600" /></a></p>
<p>You can ignore those warnings for now &#8211; you can add the metadata it is complaining about later.</p>
<p>This will add a node_modules folder in your project folder, where all our npm packages will be kept. Within that will be Gulp.</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-3.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="alignnone size-full wp-image-5179" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-3.png?resize=334%2C423&#038;ssl=1" alt="gulp-blog-3" width="334" height="423" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-3.png?w=334&amp;ssl=1 334w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-3.png?resize=237%2C300&amp;ssl=1 237w" sizes="auto, (max-width: 334px) 100vw, 334px" /></a></li>
<li>
<h4>Add a Gulpfile</h4>
<p>Next we want to add a Gulpfile, where we will define the steps for our build process. Add a JavaScript file called gulpfile.js to the root of the project, and add the following code:</p>
<pre class="striped:true lang:js decode:true">var gulp = require('gulp');

gulp.task('default', function () {
    console.log('Hello world!');
});
</pre>
<p>&nbsp;</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-2.png?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="alignnone  wp-image-5174" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-2.png?resize=884%2C418&#038;ssl=1" alt="gulp-blog-2" width="884" height="418" srcset="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-2.png?resize=1024%2C484&amp;ssl=1 1024w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-2.png?resize=300%2C142&amp;ssl=1 300w, https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/gulp-blog-2.png?w=1379&amp;ssl=1 1379w" sizes="auto, (max-width: 884px) 100vw, 884px" /></a><br />
In line 1 we load Gulp. On line 3 we define a new Gulp task. A task is a step, or a set of steps, that Gulp will execute. A task takes a function that it will run &#8211; in this case we simply log to the console. A task also has a name &#8211; here it&#8217;s called &#8220;default&#8221; and as you might guess it runs automatically when we run Gulp.</p>
<p>We can now run this task by right-clicking on the gulpfile.js and clicking the &#8220;Gulp&#8221; menu item added by the Grunt Launcher extension.</p>
<p><a href="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/Run-Gulpfile-Vid.gif?ssl=1"><img data-recalc-dims="1" decoding="async" loading="lazy" class="alignnone size-full wp-image-5172" src="https://i0.wp.com/www.cognim.co.uk/wp-content/uploads/2015/08/Run-Gulpfile-Vid.gif?resize=764%2C600&#038;ssl=1" alt="Run Gulpfile Vid" width="764" height="600" /></a></p>
<p>&nbsp;</p>
<p>Now Visual Studio is running our task, and outputting &#8220;Hello world!&#8221; to the output window. We&#8217;re done! Well, not quite&#8230;</li>
</ol>
<h2>Doing something actually useful</h2>
<p>Hello World is all well and good, but what about automating something useful? One common task is minifying CSS files, and that&#8217;s what we&#8217;ll do here.</p>
<ol>
<li>
<h4>Add the plugins</h4>
<p>Change your package.json file to the following:</p>
<pre class="striped:true lang:js decode:true">{
    "devDependencies": {
        "gulp": "3.9.0",
        "gulp-uglifycss": "1.0.4",
        "gulp-rename": "1.2.2"
    }
}
</pre>
<p>Here we&#8217;ve added two new packages, gulp-uglifycss (which minifies css) and gulp-rename (which renames files passed into it). We can now use these in our task.</li>
<li>
<h4>Modify the task</h4>
<p>Change the gulpfile.js to the following:</p>
<pre class="striped:true nums:true nums-toggle:true lang:js decode:true">var gulp = require('gulp'),
    uglifycss = require('gulp-uglifycss'),
    rename = require('gulp-rename');

gulp.task('default', function () {
    return 
         gulp.src(['./Content/*.css', '!./Content/*.min.css'])
        .pipe(uglifycss())
        .pipe(rename({
            suffix: ".min",
            extname: ".css"
        }))
        .pipe(gulp.dest('./Content'));
});
</pre>
<p>Here&#8217;s a line by line breakdown of what the task is doing:<br />
Line 1-3: Add references to the plugins we just added in our package.json<br />
Line 7: Get the CSS files from our Content directory (excluding any .min files)<br />
Line 8: Pipe (i.e. pass) the files to gulp-uglifycss, which minifies them<br />
Line 9-12:  Rename the minified files to include a .min suffix<br />
Line 13: Save the minified files back to our Content folder</p>
<p>Now, we can run this task to automatically minify all our CSS files.</p>
<p>And there we are! We now have a process that will save us from a repetitive boring task, and we can build on this to automate lots of other tasks.</li>
</ol>
<h2>Next steps</h2>
<p>Note that for brevity I have excluded everything that isn&#8217;t necessary for getting Gulp set up in Visual Studio. There are a few things you will want to do next to get fully set up:</p>
<ol>
<li>
<h4>Install the Task Runner Explorer extension</h4>
<p>You can install the <a href="https://visualstudiogallery.msdn.microsoft.com/8e1b4368-4afb-467a-bc13-9650572db708" target="_blank">Task Runner Explorer</a> Visual Studio extension to run tasks automatically on each build or every time the project opens.</li>
<li>
<h4>Install NPM Package Intellisense</h4>
<p><a href="https://visualstudiogallery.msdn.microsoft.com/65748cdb-4087-497e-a394-2e3449c8e61e" target="_blank">NPM Package Intellisense</a> gives you package intellisense when installing packages and plugins.</li>
<li>
<h4>Add more plugins</h4>
<p>Nearly any task you want to automate will <a href="http://gulpjs.com/plugins" target="_blank">have a plugin here</a> &#8211; there are over 1500 at time of writing.</li>
</ol>
<p>Happy Gulping!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.cognim.co.uk/getting-started-with-gulp-and-vs/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5148</post-id>	</item>
	</channel>
</rss>
