To those that are already used to using the .Net platform, version 4.0 and 4.5, it knows that to decrease files as js, css and others, you must use Bundle. Bundle is something fantastic and widely utilized, but I see a disadvantage, it is only used by those who develop in .Net. Its improvement and extension is limited by the ASP.NET community. Somebody can criticize my argument, I don't think it's a big argument, but why can't we use tools that other communities are using and improving all the time and thus add to our community? Microsoft comes betting on this with your new stack of development. Microsoft, from Visual Studio 2015 to the new ASP.NET, decided to give us the liberty to use Node, Bower (I did an article about both) and Gulp, something that was not developed by Microsoft, but by the Node.js community. Today's subject is about Gulp, what is and how use it in our projects. With Gulp, we going to learn to create tasks and integrate in the build of Visual Studio. Let’s go!
Sometimes I have the thought that development is easy, focusing only on the code and hearing music is something nice. However, development is not just that. It is taking care of others parts that oftentimes are boring and painful. This moment, I think again and change my mind. Have you ever had this thought? For instance, you create an application of the ground, the start is beautiful and it is following your manifest. Nevertheless, when it arrives close to the end, you notice that it still lacks many things, I am not talking about application functions, but of small things needed and done routinely. A lot of these tasks are in relationship to deployment, such as decreasing files to improve site performance. That is just an example, your team may have more tasks.
In the development of a site, many tasks are repeated and as explained above, Gulp can automate these tasks. In your site, gulpjs.com, it describes itself like “automatize and improve your workflow”. Node.js community has created Gulp. Gulp alone almost does not do too much, because it needs plug-ins to augment the task desired. For instance, do you want to decrease a file? It has a plug-in. Do you want to validate your js? It also has another plug-in. Each plug-in has a specific responsibility. The philosophy of Gulp is simple, set up the tasks through your own code . The configuration of Gulp in ASP.NET Core projects is zero, because it already comes installed. In projects legacies, you must do some steps that I am going to show below.
The first step is installing the Node.js, if you have doubts about the installation, read another article about the subject that I did before. Remember, Microsoft is investing too in Node.js, if you do not know, it is good to know from now on.
After installing Node.js, automatically it is installed the NPM. The objective of this article is not explains about Node.js, but I will do a summary: Node.js is a development platform and NPM is your package manager. With the NPM installed, go to a command-line of your computer and type in root of your web project: “NPM init”. By typing this command, it will do some tasks to be inserted in file created. Was Gulp installed? Of course not, this command serves only to create a configuration file in our project. Through this file, all node packages that I am going to install with the help of NPM will be listed. Validate in root of project if the package.json file was created with success.
After, return to command-line and type: “NPM install gulp –save-dev”. This command will install Gulp in your project and insert your dependency in the file that was created above. Now we have Gulp installed, but is not configured. For this, create a file in the root of your web project called “gulpfile.js”. This is the file responsible for receiving the tasks. Before writing some tasks, I am going to explain some structures of Gulp to improve your understanding. These are all methods used by Gulp: Task, Src, Watch, Dest, Parallel and Pipe.
Task: Method of input, create a task and your parameters are a name and a function to execute the task.
Src: Through this method is selected a file or files that must be modified after of the task.
Watch: As your own name says, it has the goal of watching a file or files that when changed is executed automatically.
Dest: This method informs the destiny where the modified file will be stored.
Pipe: Maybe the most important method, with it is executed all processes needed without expecting the end of each process. Also we can do a chain of process in the order needed.
Parallel and Series: Used in case where must execute processes in parallel.
Nice, you have an idea about Gulp and its methods, now we can go ahead. In file created, called “gulpfile.js”, add the following code and return to command-line and type: “Gulp default”.
- var gulp = require('gulp' );
-
- gulp.task('default', function () {
-
- console.log('hello world');
-
- });
If you note the response in command-line, you will see that was printed the messag was informed in the task. Realize also, to create a task we used the Task method. However, before creating a task, it was necessary to load the Gulp package, for this, it is necessary to use the Require method. According to what I said above, Gulp alone does not do too much and to improve the tasks level is needed to use others packages too. Before seeing more packages, I am going to create an application in Visual Studio 2015 and improve this project utilizing Gulp. The goal is to improve the performance.
I am going to begin the jobs with the css files, note in code below that have two styles in page layout. My idea is concatenate the files to be only one, decrease the size, pulling out spaces not used and finally, generating the styles that are not being used in the application, because when bootstrap is used, neither all styles of css are used. This tip is good to improve your site
- <link href="/Content/bootstrap.css" rel ="stylesheet" />
- <link href ="/Content/site.css" rel ="stylesheet" />
To do all the processes described above, it is necessary to install packages responsible by these processes. For this, install the packages: gulp-concat, gulp-cssmin e gulp-uncss. To install you must do the same process when Gulp was installed. Below is the code to create tasks.
- var gulp = require('gulp' );
- var concat = require('gulp-concat' );
- var uncss = require('gulp-uncss' );
- var cssmin = require("gulp-cssmin" );
-
- gulp.task('css-concat', function () {
-
- return gulp.src([ 'content/*.css', '!content/*.min.css' ])
-
- .pipe(concat('site.min.css'))
-
- .pipe(gulp.dest('content/'));
-
- });
-
- gulp.task('css', ['css-concat'], function () {
-
- return gulp.src( 'content/site.min.css')
-
- .pipe(uncss({
-
- html: [ 'http://localhost:64161/']
-
- }))
-
- .pipe(cssmin())
-
- .pipe(gulp.dest( 'content/'));
-
- });
You have already seen before as Gulp is loaded, then the new packages must be loaded this way. After declaring the variables, it is time to create the tasks and here we have two, the first to concatenate all files that are in “content” folder, and the second task is to generate the styles that are being used by the application. Note that the two tasks are to improve the css.
In the first task, it is loaded the css files of application to concatenate and excluded the css file that will be generated in the end this process, in this case the file with end “min.css”. To exclude a file is placed in front a “!”. Task in Gulp must have an input file and for this the Src method is used. The first Pipe is to concatenate the files generated. The second Pipe is to inform the destiny of file created. Observe the utilization of some packages that were installed above.
The second task is similar, except by some details. The input file is the file generated in the first task. In the first Pipe used the uncss package to compare with the html informed, which styles are being utilized. Instead of passing a page as parameter, you can pass a folder where the entire html are stored. In the second Pipe is used the cssmin package to decrease the files and last, the destiny where the file will be stored. A difference of structure between first and the second task are the parameters. In the second task is informed [‘css-concat’], that informs that this task must be executed before and thus you do not need to execute it.
Now to see the results, it must come back to command-line and type: “gulp css”. Benefits? Before creating the tasks, the application had two css of a total de 125 kb, now it has a css with a total of 8 kb, thus, less traffic and size.
But I did not finish, now I am going to work with the js files. In layout exists three js files being used. The task that I am going to create will concatenate all files and decrease to only a file.
- <script type="text/javascript" src ="/Scripts/jquery-1.10.2.js"></script>
- <script type ="text/javascript" src ="/Scripts/bootstrap.js"></script>
- <script type ="text/javascript" src ="/Scripts/respond.js"></script>
The following, the tasks to generate the file:
- var gulp = require('gulp' );
- var concat = require('gulp-concat' );
- var uncss = require('gulp-uncss' );
- var cssmin = require("gulp-cssmin" );
- var uglify = require('gulp-uglify' );
-
- gulp.task('css-concat', function () {
-
- return gulp.src([ 'content/*.css', '!content/*.min.css' ])
-
- .pipe(concat('site.min.css'))
-
- .pipe(gulp.dest('content/'));
-
- });
-
- gulp.task('css', ['css-concat'], function () {
-
- return gulp.src( 'content/site.min.css')
-
- .pipe(uncss({
-
- html: [ 'http://localhost:64161/']
-
- }))
-
- .pipe(cssmin())
-
- .pipe(gulp.dest( 'content/'));
-
- });
-
- gulp.task('js', function () {
-
- return gulp.src([ 'scripts/jquery-1.10.2.js', 'scripts/bootstrap.js' , 'scripts/respond.js', '!scripts/site.min.js' ])
-
- .pipe(concat('site.min.js'))
-
- .pipe(uglify())
-
- .pipe(gulp.dest('scripts/'));
-
- });
Now have a task called “js”, the structure it is the same, it has an input point, that is, files that are being used in the page and less the file that is processed by Gulp. After doing the concatenation, it is selected where the file will be stored. The difference in this task is the utilization of uglify package, it is responsible for decreasing and validating if error exist in the js files.
Coming back to the benefits, in the two next images it is possible to see the browser log, a before and after of changes. It is possible to see a big difference in both size and time of download. A difference between Bundle and Gulp is the process of generating a css file only by what the system is utilizing, that is, in this process the styles not used are eliminated.
Ok, we optimize our files and we are ready to deploy, but how is the development environment? Can I work with files concatenated and minifyed in dev? Of course not, because it is hard to work with these files, you will not get to do debug. Then, I am going to show a technique that helps to use files when doing development and production.
- @if(HttpContext.Current.IsDebuggingEnabled){
-
- <link href="/Content/bootstrap.css" rel ="stylesheet" />
- <link href ="/Content/site.css" rel ="stylesheet" />
-
- }
-
- else{
-
- <link href ="/Content/site.min.css" rel ="stylesheet" />
-
- }
By placing this code, the system works on a way to perfect both development and production, thus, we do not need to change in each environment.
Until now Gulp was used by command-line and that is not nice. The right way is to work automatically. And now I am going to show as integrating with build of Visual Studio. By this, I have to create more tasks according to the below:
- gulp.task('build', ['css', 'js'], function () {
-
- console.log('executing gulp build');
-
- });
This task serves only to call the others tasks created. Now we have to go in Web Property of project, Build Events and insert the code below:
cd $(ProjectDir)
gulp build
Now, each time that the project suffers a build, a task build will be executed, thus we cannot need to execute the Gulp in a manual way. Other differences between the Bundle and Gulp is that with Gulp the files are generated before publishing, already with Bundle it is generated after a system to be published, in the first request of a user.
Conclusion
To the ones that are used to developing applications in .Net, also it are used to using only tools made by Microsoft. The bundle of ASP.NET is an example, it's reliable and safe. But I think arrived at a moment in which we must see other tools in other communities and bring the cases of success. Gulp is a success in the Node.js community and in other communities. With Gulp we have millions of possibilities to create a task to help our project, because developing code is nice, but already taking care of things that take up our time is not cool.
Read more articles on Visual Studio: