Grunt and gulp are building tools for automatic compression, typescript compilation, code quality lint tools, and CSS preprocessor in the JavaScript world, which help developers handle some of the annoying repetitive tasks of client development. Both grunt and Gulp are supported in Visual Studio 2015. The ASP. NET project template uses Gulp by default.
var gulp = require(‘gulp‘);
var clean = require(‘gulp-clean‘);
var concat = require(‘gulp-concat‘);
var jshint = require(‘gulp-jshint‘);
var uglify = require(‘gulp-uglify‘);
var rename = require(‘gulp-rename‘);
var watch = require(‘gulp-watch‘);
Grunt and Gulp
What's the difference between grunt and gulp? Gulp, though a little late debut, was popular for crisp performance and elegant grammar. Unlike grunt, grunt often reads and writes files on the hard disk, Gulp uses streaming APIs to chain calls, Grunt is an early client build tool, grunt pre-defines most of the compression and unit tests that are often done. Grunt has thousands of downloads and apps every day.
Using Grunt
This instance uses empty ASP. NET project templates to demonstrate automated client building efforts. The non-empty ASP. NET project template uses Gulp by default.
The final example cleans up the target deployment directory, merges the JavaScript files, checks the code quality, compresses the contents of the JavaScript file, and deploys the directory to the Web project, and we will use the following packages:
Grunt: Task performer package;
Grunt-contrib-clean: A task to remove files and directories
Grunt-contrib-jshint: A task to review code quality
Grunt-contrib-concat: A task that connects multiple files in one file
Grunt-contrib-uglify: A task to compress and shrink file sizes
Grunt-contrib-watch: A task for detecting file activity
Prepare the Project
First, the empty Web application that creates the letter adds the sample typescript file, which, under the default settings of Visual Studio 2015, is automatically compiled into JavaScript and as a source file for grunt.
-
- In Vistual Studio 2015, create a new ASP.
-
- In the new ASP. NET Project dialog box, select the ASP. NET empty template and click the OK button.
-
- In Solution Manager, you can see the directory structure of the project, and the SRC folder contains an empty wwwroot and dependencies node
-
- Add a folder named Typescript to your project
-
- Before you add any files, confirm that Visual Studio 2015 opens the project with compile on save (under Tools, Options, text Editor->typescript=> project node)
-
- Right click on the typescript directory, click "Add New Project" Select JavaScript Project named tastes.ts (note ts suffix), copy the following code
Enum Tastes {Sweet, sour, salty, bitter}
- In the typescript directory, add a second file named Food.ts, and copy the following code
class Food {
constructor(name: string, calories: number) { this._name = name; this._calories = calories;
}
private _name: string;
get Name() { return this._name;
}
private _calories: number;
get Calories() { return this._calories;
}
private _taste: Tastes;
get Taste(): Tastes { return this._taste }
set Taste(value: Tastes) { this._taste = value;
}
}
Configure NPM
Next, configure NPM to come down grunt and grunt-tasks
- In the solution directory, right-click and select Add New project, select NPM configuration file, leave the default file name, and click the OK button
- In the Package.json file, under the Devdependencies property, enter grunt, use only the prompt to select Grunt and enter, add a colon, and use smart hints to select a version number
- Add more dependent items that we need
- Save File
These packages will be downloaded automatically, and you can see the downloaded content in the Node-modules directory, if you open "Show All Files"
If necessary, you can restore these packages by right-clicking NPM under Dependences and selecting the Restore Packages button
Configure Grunt
Grunt uses a file list named Gruntfile.js to configure, load, and register tasks so that it can be run manually or automatically by the cardinality vistual Studio event mechanism
-
- Right-click the project file, select "Add New Project", select "Grunt configuration file" option, leave the default file name, and click the Add button
The initial file contains the Grunt.initconfig () method, which is where we set the options
module.exports = function (grunt) {
grunt.initConfig({
});
};
-
- In the previous method, add a clean task, which can add an array to define the directory or file to be cleaned
module.exports = function (grunt) {
grunt.initConfig({
clean: ["wwwroot/lib/*", "temp/"],
});
};
-
- Below the Initconfig method, we need to call the Grunt.loadnpmtasks method to have the task run in Visual Studio
Grunt.loadnpmtasks ("Grunt-contrib-clean");
-
- Save this file with the contents of the file as shown below
module.exports = function (grunt) {
grunt.initConfig({
clean: ["wwwroot/lib/*", "temp/"],
});
grunt.loadNpmTasks("grunt-contrib-clean");
};
-
- Right-click on Gruntfile.js and select "Task Runner Explorer"
-
- Verify that the clean task is already present under the Tasks node
-
- Right click on the clean task, select Run, a command line form to display, and perform the defined task
-
- In the Initconfig method, add the Concat task
The SRC attribute defines the list of files to be linked, the Dest property defines the target file for the merge to complete, and the all property defines the tasks that will be executed in any build environment
module.exports = function (grunt) {
grunt.initConfig({
clean: ["wwwroot/lib/*", "temp/"],
concat: {
all: {
src: [‘TypeScript/Tastes.js‘, ‘TypeScript/Food.js‘],
dest: ‘temp/combined.js‘ }
},
});
grunt.loadNpmTasks("grunt-contrib-clean");
};
- Add Jihit Task
The Jihit Code quality tool will run in all JS files in the temp directory
jshint: {
files: [‘temp/*.js‘],
options: { ‘-W069‘: false,
}
}
-
- Add Uglify Task
SRC defines a list of confusing source files, Dest defines the target file
uglify: {
all: {
src: [‘temp/combined.js‘],
dest: ‘wwwroot/lib/combined.min.js‘ }
},
-
- Finally, call Grunt.loadnpmtasks () to have all of the tasks defined above execute in Visual Studio
- Save the file, the final file content is as follows
module.exports = function (grunt) {
grunt.initConfig({
clean: ["wwwroot/lib/*", "temp/"],
concat: {
all: {
src: [‘TypeScript/Tastes.js‘, ‘TypeScript/Food.js‘],
dest: ‘temp/combined.js‘ }
},
jshint: {
files: [‘temp/*.js‘],
options: { ‘-W069‘: false,
}
},
uglify: {
all: {
src: [‘temp/combined.js‘],
dest: ‘wwwroot/lib/combined.min.js‘ }
},
});
grunt.loadNpmTasks("grunt-contrib-clean");
grunt.loadNpmTasks(‘grunt-contrib-jshint‘);
grunt.loadNpmTasks(‘grunt-contrib-concat‘);
grunt.loadNpmTasks(‘grunt-contrib-uglify‘);
};
-
- You will find that the tasks defined above already appear in the Task Runner Explorer
Perform these tasks sequentially,
Integrate them
Use the Grunt.registertask method to register a task that runs a sequence of specified orders, for example, the order of the tasks above should be clean->concat->jshint->uglify. Add the following code to the file, and keep the method call and the Loadnpmtasks call when the sibling
Grunt.registertask ("All", [' Clean ', ' concat ', ' jshint ', ' uglify ']);
Now you can find an alias task named All in the task Runner Explorer, and run it to execute all the tasks in the above sequence.
Monitoring file Changes
Watch tasks can monitor changes in files and directories, and trigger a series of tasks after monitoring changes, adding the following code to the Initconfig method to monitor changes to all JS files in the typescript directory and perform the ' All ' task
watch: {
files: ["TypeScript/*.js"],
tasks: ["all"]
}
Add a Loadnpmtask method call to have the task appear in the Task Runner Explorer
grunt.loadNpmTasks(‘grunt-contrib-watch‘);
Run the watch task, the command-line form will be in the waiting state, when it monitors the file changes, opens a typescript file, adds anything, and you'll find it's already working.
Collaborating with Visual Studio events
In addition to running these tasks manually, you can also bind these tasks to Visual Studio events, and automatically run defined tasks when Visual Studio triggers a given event
In the Task Runner Explorer, right-click on the Watch task and select "Bindings->project open", when you open the project, the watch task will automatically execute and observe the file changes and perform the series of tasks defined above
Using Gulp
In addition to some notable differences, Gulp's configuration files are very similar to grunt, and the examples below compare grunt examples but use gulp packages and conventions.
The different NPM packages
As with grunt, the gulp definition is also in the Devdependencies attribute of the Ackage.json file, as shown in the following article, and you can update to the nearest version number only by prompting.
{
"version": "1.0.0",
"name": "GruntFromEmptyWebApp",
"private": true,
"devDependencies": {
"gulp": "3.8.11",
"gulp-clean": "0.3.1",
"gulp-jshint": "1.11.0",
"gulp-concat": "2.5.2",
"gulp-uglify":"1.2.0",
"gulp-rename": "1.2.2",
"gulp-watch": "4.2.4"
}
}
Differences between the gulpfile and gruntfile examples
Replace Gruntfile.js, add a file named Gulpfile.js, and in this file, use the node. js method require () to assign values to several variables in the following
Under the assignment statement, call Gulp's Task method, the first parameter is the string representation of the name of the task, and the second argument is a callback method
gulp.task(‘default‘, function () {
// place code for your default task here
});
At this point, a task named default already exists in the task Runner Explorer, although it is empty
Within the callback function of the task method, use the gulp defined to perform the work we need, first defining a clean task
gulp.src(‘wwwroot/lib/*‘).pipe(clean());
Gulp Flow
Gulp is a streaming object that contains the SRC, pipe, and Dest methods
- The SRC () method is used to define where the stream comes from
- The pipe () method defines how the stream is rewritten
- The Dest () method defines the output of the stream
The usual pattern of code is shown in the following article
gulp.src()
.pipe()
.pipe()
.pipe(dest());
The SRC method gets the initial original stream file, executes the convection operation after a series of pipe calls, and finally outputs the final result through the Dest () method, which has the advantage of having only one input and one output to make the task execute faster.
Integration
The following is a series of tasks for our Organization, defining it as all, and the tasks performed are exactly the same as those in grunt above
gulp.task("all", function () {
gulp.src(‘wwwroot/lib/*‘).pipe(clean());
gulp.src([‘TypeScript/Tastes.js‘, ‘TypeScript/Food.js‘])
.pipe(concat("combined.js"))
.pipe(jshint())
.pipe(uglify())
.pipe(rename({
extname: ‘.min.js‘ }))
.pipe(gulp.dest(‘wwwroot/lib‘))
});
The watch task is also very similar to the grunt example
gulp.task("watch", function () {
gulp.watch("TypeScript/*.js", [‘all‘]);
});
Using the same approach, binding Visual Studio events in the Task Runner Explorer allows the watch task to be executed automatically when the project is opened.
Ethane
Original link: http://docs.asp.net/en/latest/client-side/grunt-gulp.html
ASP.NET5 Client Development: Efficient application of grunt and Gulp build tools in Visual Studio 2015