Настройки Gulp-тасков в Visual Studio Code
Вообще, эти инструменты настолько хороши, что грядущий релиз ASP.NET отказался от своей фирменной комплектации и диспетчеров задач в пользу широко используемых обществом инструментов. А теперь они являются главными элементами в Visual Studio и Visual Studio Code. Сегодня я покажу вам как использовать Gulp в Visual Studio Code, чтобы запустить следующие наиболее часто используемые задачи:
- Компиляция TypeScript в JavaScript
- Компиляция SCSS-файла в чистый CSS
- БОНУС — Добавление пары заданий для автоматического создания JS и CSS при изменения кода
Хотя Gulp является автономным инструментом, VS Code имеет отличную внешнюю поддержку для него. Это означает, что до тех пор, пока у вас есть gulpfile.js в корневом каталоге вашего проекта, VS-код будет использовать его для создания задач, доступных в IDE. Давайте начнем:
Создание проекта
Я предполагаю, что вы уже установили TypeScript и VSCode. Если нет, посмотрите здесь. Для создания проекта выберите нужное местоположение и создайте новый каталог по имени VSGulpTest .
Инсталляция npm и Gulp
Начнем с начала. Npm — менеджер пакетов Node (отсюда и название) и для того, чтобы получить его вам нужно установить Node.js. Это можно сделать двумя способами:
- с помощью chocalateyNuget choco install nodejs
- с помощью исполняемого файла, скаченного с официального сайта
Теперь нам ничто не мешает установить Gulp. Наберите в командной строке Node.js следующее: npm install —global gulp и нажмите клавишу Enter для выполнения. Эта команда устанавливает Gulp глобально. Я cтараюсь избежать глобальных установок, но, установленный локально, Gulp не будет работать в Visual Studio Code. Все остальные пакеты будут установлены локально.
Далее, нам необходимо инициализировать npm на текущем проекте. Для этого откройте командную строку Node.js, перейдите в корневой каталог вашего проекта и выполните следующую команду: npm init

В результате в корневом каталоге вашего проекта будет создан файл package.json. Этот файл используется Node.js для отслеживания установленных пакетов. Командная строка проведет вас через последовательность вопросов (Wizard CLI) для того, чтобы сгенерировать параметры конфигурации. Ни один из этих параметров не является особенно важным, вы можете оставить все из них пустыми, или скопировать мои настройки. На последнем шаге просто наберите yes для создания файла.
Установка необходимых пакетов
Gulp – это простой диспетчер задач, поэтому сам по себе он особо пользы не несет. Нам нужны плагины, чтобы помочь нам выполнить доставленные задачи, а именно: typescript, merge и sass. Чтобы установить плагины, вернитесь к командной строке Node.js, перейдите в корневой каталог вашего проекта, а затем выполните следующие команды, по одной за раз:
Эти команды будут устанавливать необходимые плагины и ряд зависимостей. Эти плагины будут вызываться из Gulp для выполнения наших задач.
Добавляем код
Прямо сейчас наш проект пуст. Давайте добавим пару TypeScript файлов, файл Sass и HTML-файл, чтобы сделать набросок сайта. Создайте файлы animal.ts и human.ts и вставьте соответствующий код.
Создайте файл main.scss для CSS кода и файл index.html для главной страницы сайта. И снова используйте код ниже, или добавьте свой собственный код в соответствующие файлы.
Добавляем Gulp-таски
Пришло время соединить все вместе и получить рабочий сайт. В корневом каталоге вашего проекта создайте файл gulpfile.js и добавьте следующий код:
Я постараюсь кратко объяснить, что происходит в этом файле. В верхней части файла мы импортируем все плагины, после чего создаем 3 задачи:
scripts компилит *.ts файлы в *.js, объединяет весь код в один файл, генерирует файлы (.d.ts) и сохраняет созданные файлы в указанном месте ( release ) sass компилит *.scss файлы в *.css и помещает созданный файл в указанном месте ( css ) watch мониторит изменение файлов *.scss и *.ts на наличие каких-либо изменений и автоматически выполняет соответствующую задачу
Теперь мы почти готовы к запуску. Находясь в Visual Studio Code, нажмите клавиши Ctrl+Shift+B для определения нового диспетчера задач.

Нажмите на Настроить средство выполнения задач. Это выведет файл tasks.json. Удалите все, что в нем есть и добавьте следующий код:
Этот код дает указание Visual Studio Code использовать Gulp в качестве главного диспетчера задач, а внутри мы объявляем 3 задачи, которые мы хотим сделать доступными для IDE. Они должны соответствовать задачам, определенным в файле gulpfile.js . Вы всегда можете пропустить не нужные вам задачи, но любая новая задача должна быть определена в gulpfile.js первой.
Если вы нажмете клавиши Ctrl+Shift+P и выберите Run Task (запуск задачи), перед вами будет раскрывающийся список задач, которые мы перечислили в файле tasks.json. Выберите таск watch и запустите его. Вы заметите, что Окно Вывода (Output Window) находится в фокусе, а в нижнем левом углу есть бегунок, дающий понять, что задача в данный момент активна.
Каждый раз, когда вы делаете изменения в *.scss, или *.ts файлах и сохраняете результат, будет вызываться соответствующая задача для выполнения. После этого вам нужно будет обновить страницу в браузере, чтобы увидеть как изменилась ваша страница.
Чтобы остановить задачу нажмите клавиши Ctrl+Shift+P и выберите Terminate running task (Завершить запущенную задачу). К счастью, IntelliSense запускается практически в самом начале, поэтому вручную много печатать вам не придется.
Также, вы можете установить пакет npm-livereload вместе с соответствующим плагином для браузера, который позволит вам автоматически обновлять тестируемую страницу каждый раз, когда есть изменения в отслеживаемых файлах.
How to run gulp task in visual studio code?
I have opened my work-space in Visual Studio Code and I have setup gulp tasks. Now I am running gulp tasks in CMD windows. Have do I run gulp tasks directly from VS Code?
Say I have gulp tasks for
- Test
- Serve
- Build
1 Answer 1
Normally VS code auto detect gulp task.
As you can see in this doc
Pressing F1 and then typing Run Task followed by Enter will list all available tasks. Selecting one and pressing Enter will execute the task.
Setting up a Gulp task with Visual Studio Code
As a web developer, certain tools have become indispensable. I can’t even imagine having to do any front-end work without [npm](https://www.npmjs.com/" target="_blank), [Grunt](http://gruntjs.com/" target="_blank) or [Gulp](http://gulpjs.com/" target="_blank). In fact, these tools are so great that the upcoming release of ASP.NET has thrown away proprietory package and task managers in favour of the widely adopted and established tools used by the community. And these tools are now first class citizens both in Visual Studio and Visual Studio Code.
Classic .NET developers and avid Visual Studio users will have a lot of catching up to do. But we are here to help! Today, I will show you how to use Gulp in Visual Studio code in order to run some basic tasks. Although there is a crazy amount of tasks that you can setup, we will focus on 2 (+1 bonus) things:
- Compiling TypeScript to JavaScript
- Compiling a Saas (CSS) file to pure css
- BONUS — Adding a couple of watch tasks to automatically build js and css when the code’s changed
Although Gulp is a stand-alone tool, VS Code has excellent support for it out-of-the box. What this means is that as long as you have a gulpfile.js at the root of your project, VS Code will happily pick it up and make the tasks available in the IDE. Let’s get started:
Create a project
I assume that you already have TypeScript and VSCode installed. If not, have a look [here](GHOST_URL/typescript-and-vs-code/" target="_blank). To create a project, you need a folder in the file system. Choose your preferred location and create a new directory with name VSGulpTest .
Install npm and Gulp
We will start from the basic. Npm is Node’s package manager (hence the name, in case you missed it) and in order to get it you need to install Node.js. There are two ways to do it:
- Using chocalateyNuget choco install nodejs
- Download the executable from the [official site](https://nodejs.org/en/" target="_blank)
With this out of the way, you can now install Gulp. Open the Node.jS Command Prompt and type npm install —global gulp . Press enter to execute. This command installs Gulp globally. I generally tend to avoid global installs but for VSCode will not run Gulp if only installed locally. All subsequent packages will be installed at the local level through.
Next, we need to initialize npm on the current project. To do so, open the Node.js command prompt, navigate to the root of your project and execute the following command: npm init

This task will create a package.json file at the root of your project. This file is used by node.js to keep track of the installed packages. The command prompt will take you through a set of questions (CLI Wizard) in order to generate the configuration settings. None of the settings is particularly important so you could either leave all of them blank or copy my settings. At the last step, just type yes to generate the file.
Install necessary packages
Gulp is a task runner so on its own it’s pretty useless. We need plugins to help us perform the necessary tasks. For the purpose of this post, we need 3 plugins:
- typescript
- merge
- sass
To install the plugins, go back to the node.js command prompt and navigate to the root of your project. Then execute the following commands, one at a time:
These commands will install the necessary plugins and a number of dependencies. These plugins will be called from gulp to perform our tasks.
Add some code
Right now, our project is empty. Let’s add a couple of TypeScript files, a Sass file and an HTML file to make a crude, yet basic website. Add animal.ts and human.ts files and paste the appropriate code. Add a main.scss file for the CSS code and an index.html file for the main website page. Again, use the code below or add your own code to the appropriate files
Add the Gulp tasks
Time to glue everything together and get a working site. At the root of your project, create a gulpfile.js file. Add the following code:
I will try to explain briefly what’s happening within this file. At the top of the file we define gulp we import all the plugins. Then we create 4 tasks:
- scripts — compiles the *.ts files to js, merges all code into one file, generated the typings (.d.ts) file and saves the generated files to the designated location ( release )
- sass — compiles the *.scss files to *css and puts the generated file in the designated location ( css )
- watch — monitors the *.scss & *.ts files for any changes and automatically executes the corresponding task
Now we are ready to run — almost. While in VS Code, press Ctrl+Shift+B to define a new task runner.

Press on **Configure Task Runner" option. This will present you with the tasks.json file. Delete everything from the file and add the following code:
This code instructs VS Code to use Gulp as the main task runner and inside there we declare the 3 tasks we wish to make available to the IDE. They need to correspond to the tasks we defined in the gulpfile.js file. You can always omit tasks you don’t need but any new task needs to be defined in the gulpfile.js first.
Next, if you type Ctrl+Shift+P and then type Run Task, you’ll be presented with a drop-down with the tasks we defined in the tasks.json file. Select the watch tasks and let it run. You’ll notice that the Output Window is brought to focus and there is a small spinner at the bottom left-hand corner to indicate that the task is currently active.
Every time you do a change to a *.scss or *.ts file and you save the file, the change will trigger the corresponding task to execute. If you have your index.html page open on the browser, all you have to do is refresh and you’ll see the changes instantly.
To stop the task, simply type Ctrl+Shift+P and then type Terminate running task. This will kill the running process. Luckily, IntelliSense kicks in quite early so you don’t have to type all that — limited keystrokes/lazy etc.
Up your game
If you wish to take this to the next level, you can install the [npm-livereload](https://www.npmjs.com/package/livereload" target="_blank) package along with the appropriate browser plugin that will allow you to automatically refresh the page you’re testing every time there’s a change in the watched files. If you want to see this in action or an example, let me know in the comments.
Congratulations in creating your first Gulp task and running it withing VS Code.
Food for thought
Please note that this is not the only way to run Gulp or Grunt and some may advocate that you shouldn’t be so dependent on IDEs. VS Code was designed to be lightweight and fast by getting rid the massive bulk that comes with the full Visual Studio IDE. Therefore, adding task dependencies and instantiating them through the IDE may not be the best idea after all. You can always use the Node.js command prompt to kick off all these tasks in the exact same way and expected behavior. If you don’t like the approach I used above, feel free to use the right tool that makes you feel comfortable.
Let me know what you think in the comments and if you have a favorite Gulp plugin that we should know about.
Как запустить gulp консоль в vs code
Pressing F1 and then typing Run Task followed by Enter will list all available tasks. Selecting one and pressing Enter will execute the task.
Установка node + gulp для Windows 10

Установка node js





Как запустить консоль Windows 10 PowerShell


Узнать версию node js
Установка Gulp под Windows 10

- Запускаем PowerShell от имени администратора
- Проверяем текущие параметры для политики выполнения: Get-ExecutionPolicy -List
- Устанавливаем требуемый уровень (меняем политику выполнения) Set-ExecutionPolicy -Scope LocalMachine Unrestricted
- Проверяем версию Gulp, если после ввода gulp -v, вы видите CLI version: 2.2.0, значит установка прошла успешно.

How to use Gulp in Visual Studio
Gulp calls itself the streaming build system. No, this isn’t a replacement for build systems like msbuild or nant. In this case, we are talking about building the client side parts of our applications like JavaScript files, StyleSheets (CSS, SASS or LESS) and HTML files.
The basic idea with Gulp is that you use pipes to stream a set of data (usually files) through some kind of processing. As it turns out, it is pretty easy to use and is probably best described using an example.
Installing Node and Gulp
If you don’t already have it installed, download and install node.js.
If you are using VS 2015 and ASP.NET 5, Visual Studio will install npm and gulp for you automatically.
Once node is installed, we need to install gulp using the node package manager (npm). From the command line, run
npm install gulp -g
Setting up your Visual Studio project
Rather than create a new sample project here, I’m going to use the Hot Towel SPA template from John Papa. First, I will create an new empty web application and then install the HotTowel.Angular nuget package.
I wanted to use this template as an example because it is a perfect candidate for Gulp. The application is written using AngularJS and the code is split across 14 different JS files. From a code maintenance / readability standpoint, it is definitely good to split the code into files like this. From an application loading performance standpoint however, loading 14 separate JS files is generally not a great idea.
Here is a snapshot of the traffic captured using Fiddler.
![]()
Let’s see what we can do to fix this using Gulp.
Initializing our project for Gulp
First, we need to create a package.json file in the root directory of the your project. We can do this by running npm init on the command line or simply creating a file with the following contents:
Next, we will install a few packages that we will use for this project. Run the following commands from the same folder that you added the package.json file.
Note, the —save-dev option here is telling node to add these packages to a devDependencies section in the package.json file and install the packages in a node_modules folder in the current folder . At any time, you or another developer on your team can re-install all the devDependencies by simply running npm install .
Finally, create a gulpfile.js file in the same folder.
Now, run gulp from the command line and you should see some output stating that scripts task is completed successfully.
![]()
This will have created an all.min.js file that contains minified JavaScript from all the js files in the app folder.
Now we include all.min.js in the Visual Studio project and replace the 14 separate script includes with a single include to the new script.
Now, we can see that when our application loads, a single JS file is needed.
![]()
Watching for changes
Wouldn’t it be nice gulp could automatically re-run the scripts task whenever we make a change any of our js files? Sure, we can do that!
Add the following to our gulpfile.js:
Now, if we run gulp watch from the command line, our new watch task will watch for changes to any of our js files. When a change is detected it will trigger the scripts task to execute, regenerating the all.min.js file.
![]()
You can learn more about gulp.watch here. Note that at this time, the built in gulp.watch has some bugs that stop it from watching new files. These should be fixed soon but in the mean time you might want to use use the popular gulp-watch plugin.
Integrating with Visual Studio
So far, we have been working primarily in the command line. It would be nice if we could integrate with our existing Visual Studio experience.
Luckily, we can with the new Task Runner Explorer plugin. Once the plugin is installed, open the Task Runner Explorer from the View –> Other Windows –> Task Runner Explorer menu.
This window will show you all the tasks in the gulp file and allow you to bind those tasks to certain Visual Studio events. This way, we don’t need to remember to run the gulp tasks from the command line. The IDE can handle it for us.
What I like to do is bind the watch task to the Solution Open event and bind the scripts task to the Before Build event.
![]()
With these bindings, we can make sure that all.min.js is correctly generated when we build the application and also regenerated anytime I make changes to the js files.
The Task Runner Explorer also shows the output of any running tasks. Here you can see the output from the watch task, which is always running in the background in this configuration.
![]()
Development vs Production
To simplify debugging, you may want to include all your individual scripts in a development build and only include the single concatenated/minified script in your production build. Take a look at my post on Web Optimization in ASP.NET Core MVC for some ideas on how to this can be accomplished. That post covers ASP.NET Core MVC but a similar approach could be used in MVC 5. With the following in your cshtml file, the individual files would be included when debug=”true” is set in your web.config. If debug=”false”, then only the single concatenated/minified file is included.
Note that this only works for cshtml files in an MVC application as it requires the Razor view engine.
So, now we’ve seen a very simple example of bundling and minification. As many have pointed out, this could have easily been accomplished with the runtime bundling in MVC5 provided by System.Web.Optimization. I have a few thoughts on this:
Runtime vs. Compile-Time Optimizations
System.Web.Optimization takes the approach of bundling/minifying your assets at runtime. The first time someone asks for a bundle, it will combine and minify all the files in that bundle and cache the results for the next request. While the cost of this is minimal, it has always seemed to me that it is a strange to use server resources to do this task. At the time of publishing our application to the server, we already know what the code is. To me it makes more sense to do this step on the build server or on the developer machine BEFORE publishing the code. Task runners like Gulp take the approach of doing these asset optimization steps at compile/build time.
Note that there are some specific use cases such as CMS tools that require runtime optimizations because the assets might not be known at compile time. For the vast majority of applications, I think the task runner approach is more logical.
Extensibility and Consistency
There is no question that the runtime bundling in MVC 5 provides a better ‘out-of-the-box’ experience. When you create a new project, bundling and minification is setup and working. It is easy to add new files. People generally understand the concepts and don’t need to spend a lot of time fiddling with the bundle configuration. Where System.Web.Optimization starts to fall apart for me is when I want to take things 1 step further.
What if I want to start using a CSS pre-processor like LESS or SASS? There is no way built-in way to tie CSS pre-processors into System.Web.Optimization. Now I need to start looking for VS plugins or extensions to System.Web.Optimization. If we’re lucky, these will work well. In my experience they have some problems, are often out-of-date or are just not available. One big problem with using VS plugins is that I can’t make use of those on the build server. Another problem is trying to make sure that everyone on the team has the right plugins installed.
With Gulp, all I need to do is include a gulp plugin (eg, gulp-less) and add the less compilation step to my stylesheet pipeline. It would be a 1 or 2 line change to my gulp file. The node package manager is able to ensure that everyone on the team has the right gulp plugins installed. Since everything is command line based, it is also very easy to call the same tasks from the build server if necessary.
So the big advantages are extensibility and consistency. System.Web.Optimization is very good at doing a couple things, but it is also limited to doing those couple of things. When we want to take things a little further, we start to run into some pain points with ensuring a consistent development environment. Gulp on the other hand is extremely flexible and extensible in a way that makes it easy to provide consistency for your team.
Wrapping it up
This post really only scratched the surface of what is possible with Gulp. There are 1,000’s of Gulp plugins available for pretty much everything you can imagine. This is not limited to JavaScript files. You could be processing stylesheets, images or audio.
My typical pipeline for scripts in a SPA is TypeScript Lint => SourceMaps => TypeScript Compile => Concat => Uglify. With the magic of a gulp-watch, this all happens anytime I make a change to my typescript file. The only script files I commit to source control are the TypeScript files. The compiled JavaScript and concatenated files do not need to be checked in because they can be generated at any time using Gulp. The build server is responsible for doing that before publishing the application to the server.