Npm
Содержание:
Введение
Gulp — это таск-менеджер для автоматического выполнения часто используемых задач
(например, минификации, тестирования, объединения файлов), написанный на
языке программирования JavaScript.
Программное обеспечение использует
командную строку для запуска задач, определённых в файле Gulpfile.
Создан как ответвление от проекта Grunt, чтоб взять из него лучшие практики.
Распространяется через менеджер пакетов
NPM
под MIT лицензией.
Если Вы будете копировать код с этой страницы — имейте в виду, что я ставлю кое-где лишние
проблелы — исключительно для того, чтобы текст лучше помещался на экран. Смело удаляйте их.
Это основная статья об использовании Gulp.
В данный момент Вы можете помимо этой прочитать также статьи:
|
Как скопировать папку с помощью Gulp |
|
|
Объединить и сжать несколько css файлов в один |
|
|
Как отправить файлы по ftp с помощью Gulp |
|
|
Gulp series |
|
|
Обработка только изменённых файлов с помощью gulp.watch().on(‘change’) |
Плагины
Вместе с Gulp вы можете использовать ряд плагинов — более 600 на деле. Вы найдёте их список на странице плагинов, либо путём поиска gulpplugin в npm. Некоторые плагины помечены «gulpfriendly»; это не плагины, но они предназначены для работы с Gulp. Учтите, что при поиске непосредственно в npm, вы не увидите плагины из чёрного списка (прокрутите страницу с плагинами вниз и увидите больше).
Большинство плагинов довольно просты в использовании, имеют хорошую документацию и запускаются аналогичным образом (через поток файловых объектов). Они, как правило, модифицируют файлы (хотя некоторые, вроде валидаторов, нет) и возвращают новые файлы, которые передаются в следующий плагин.
Давайте расширим уже упомянутую задачу js:
Мы используем три плагина: gulp-jshint, gulp-uglify и gulp-concat. Вы можете увидеть в файлах README для плагинов, что их довольно легко использовать. Доступны некоторые настройки, но по умолчанию, как правило, всё хорошо.
Вы, возможно, заметили, что плагин JSHint вызывается дважды. Потому что первая строка вызывает JSHint для файлов, которые только присоединяют свойство jshint к файловым объектам без какого-либо вывода. Вы можете прочитать свойство jshint самостоятельно или передать его в jshint.reporter по умолчанию или в другой reporter, такой как jshint-stylish.
Два других плагина понятнее: функция uglify() минимизирует код, а функция concat(‘app.js’) объединяет все файлы в один с именем app.js.
Sample gulpfile.js
This file is just a quick sample to give you a taste of what gulp does.
var gulp =require('gulp4');var less =require('gulp-less');var babel =require('gulp-babel');var concat =require('gulp-concat');var uglify =require('gulp-uglify');var rename =require('gulp-rename');var cleanCSS =require('gulp-clean-css');var del =require('del');var paths ={ styles{ src'src/styles/**/*.less', dest'assets/styles/'}, scripts{ src'src/scripts/**/*.js', dest'assets/scripts/'}};functionclean(){returndel('assets');}functionstyles(){returngulp.src(paths.styles.src).pipe(less()).pipe(cleanCSS()).pipe(rename({ basename'main', suffix'.min'})).pipe(gulp.dest(paths.styles.dest));}functionscripts(){returngulp.src(paths.scripts.src,{ sourcemapstrue}).pipe(babel()).pipe(uglify()).pipe(concat('main.min.js')).pipe(gulp.dest(paths.scripts.dest));}functionwatch(){gulp.watch(paths.scripts.src, scripts);gulp.watch(paths.styles.src, styles);}exports.clean= clean;exports.styles= styles;exports.scripts= scripts;exports.watch= watch;var build =gulp.series(clean,gulp.parallel(styles, scripts));gulp.task('build', build);gulp.task('default', build);
Gulp rename files example
In the following example, we use the plugin
to rename our files.
ls src/ about.htm contact.htm index.htm
Inside the directory, we have three HTML files. We want
to rename their extensions to .html.
$ nmp i --save-dev gulp-rename
We install the plugin.
gulpfile.js
const { src, dest } = require('gulp');
const rename = require('gulp-rename');
function renameFiles() {
return src('src/*.htm')
.pipe(rename({ extname: '.html' }))
.pipe(dest('dist/'));
}
exports.rename = renameFiles;
We create the task. It renames all
files in the directory and copies them into the
directory.
return src('src/*.htm')
.pipe(rename({ extname: '.html' }))
.pipe(dest('dist/'));
With the function, we create a source strean from htm files
in the directory. We use globbing to select htm files only.
The function takes the data from the stream and applies the
function on it.
With the function, we specify the output stream; it is the
directory where we copy the renamed files.
$ gulp rename Using gulpfile ~/Documents/prog/js/gulp-lib/gulpfile.js Starting 'rename'... Finished 'rename' after 35 ms
With the tool, we run the task.
$ ls dist/ about.html contact.html index.html
The files were renamed.
The gulp-minify example
The plugin minifies JS files.
$ npm i --save-dev gulp-minify
We install the plugin.
src/js/main.js
function hello() {
return 'Hello there!';
}
hello();
We have a simple file with a function.
gulpfile.js
const { src, dest } = require('gulp');
const minify = require("gulp-minify");
exports.default = () => {
return src('src/js/main.js', { allowEmpty: true })
.pipe(minify({noSource: true}))
.pipe(dest('dist/js'))
}
We read the JS file, pass it through the function
and write the result into the directory.
$ gulp Using gulpfile ~/Documents/prog/js/gulp-lib/gulpfile.js Starting 'default'... Finished 'default' after 75 ms
We run the default Gulp task.
$ cat dist/js/main-min.js
function hello(){return"Hello there!"}hello();
These are the contents of the minified
file.
works great with lazypipe
Lazypipe creates a function that initializes the pipe chain on use. This allows you to create a chain of events inside the gulp-if condition. This scenario will run jshint analysis and reporter only if the linting flag is true.
var gulpif =require('gulp-if');var jshint =require('gulp-jshint');var uglify =require('gulp-uglify');var lazypipe =require('lazypipe');var linting =false;var compressing =false;var jshintChannel =lazypipe().pipe(jshint).pipe(jshint.reporter).pipe(jshint.reporter,'fail');gulp.task('scripts',function(){returngulp.src(paths.scripts.src).pipe(gulpif(linting,jshintChannel())).pipe(gulpif(compressing,uglify())).pipe(gulp.dest(paths.scripts.dest));});
Usage
var gulp =require('gulp');var webpack =require('gulp-webpack');gulp.task('default',function(){returngulp.src('src/entry.js').pipe(webpack()).pipe(gulp.dest('dist/'));});
The above will compile into assets with webpack into with the output filename of (webpack generated hash of the build).
You can pass webpack options in with the first argument, including which will greatly increase compilation times:
returngulp.src('src/entry.js').pipe(webpack({ watchtrue, module{ loaders{ test\.css$, loader'style!css'},,},})).pipe(gulp.dest('dist/'));
Or just pass in your :
returngulp.src('src/entry.js').pipe(webpack(require('./webpack.config.js'))).pipe(gulp.dest('dist/'));
If you would like to use a different version of webpack than the one this plugin uses, pass in an optional 2nd argument:
var gulp =require('gulp');var webpack =require('webpack');var gulpWebpack =require('gulp-webpack');gulp.task('default',function(){returngulp.src('src/entry.js').pipe(gulpWebpack({}, webpack)).pipe(gulp.dest('dist/'));});
Pass in 3rd argument if you want to access the stats outputted from webpack when the compilation is done:
var gulp =require('gulp');var webpack =require('gulp-webpack');gulp.task('default',function(){returngulp.src('src/entry.js').pipe(webpack({},null,function(err,stats){})).pipe(gulp.dest('dist/'));});
A common request is how to handle multiple entry points. You can continue to pass in an option in your typical webpack config like so:
var gulp =require('gulp');var webpack =require('gulp-webpack');gulp.task('default',function(){returngulp.src('src/entry.js').pipe(webpack({ entry{ app'src/app.js', test'test/test.js',}, output{ filename'.js',},})).pipe(gulp.dest('dist/'));});
var gulp =require('gulp');var webpack =require('gulp-webpack');var named =require('vinyl-named');gulp.task('default',function(){returngulp.src('src/app.js','test/test.js').pipe(named()).pipe(webpack()).pipe(gulp.dest('dist/'));});
The above stream will add a property to the vinyl files passing through. The stream will read those as entry points and even group entry points with common names together.
Ошибки
SKIPPING OPTIONAL DEPENDENCY: fsevents
Ошибка при установке gulp. Вы выполняете
$ npm install gulp —save-dev
А на выходе
npm WARN saveError ENOENT: no such file or directory, open ‘C:\Users\ao\Desktop\Sites\heihei\package.json’
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open ‘C:\Users\ao\Desktop\Sites\heihei\package.json’
npm WARN heihei No description
npm WARN heihei No repository field.
npm WARN heihei No README data
npm WARN heihei No license field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {«os»:»darwin»,»arch»:»any»} (current: {«os»:»win32″,»arch»:»x64″})
+ gulp@4.0.2
added 314 packages from 217 contributors and audited 6490 packages in 30.037s
found 0 vulnerabilities
Скорее всего Вы не инициализировали npm. Нужно выполнить
npm init
Ввести нужные данные (либо просто нажимать Enter), после чего создастся файл package.json и можно будет вернуться к установке gulp
Unhandled ‘error’ event
events.js:174
throw er; // Unhandled ‘error’ event
^
CssSyntaxError: postcss-simple-vars: C:\Users\ao\Desktop\Sites\travel-site\app\assets\styles\modules\_large-hero.css:5:2: Undefined variable $aMadeUpVariable2
Может быть вызвана, например, несуществующей переменной. Допустим Вы добавили цвет
как переменную, но нигде её не задали.
Unexpected identifier
Если Вы запустили Gulp
gulp
И получили что-то похожее
SyntaxError: Unexpected identifier
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at execute (C:\Users\ao\AppData\Roaming\npm\node_modules\gulp-cli\lib\versioned\^4.0.0\index.js:36:18)
at Liftoff.handleArguments (C:\Users\ao\AppData\Roaming\npm\node_modules\gulp-cli\index.js:201:24)
at Liftoff.execute (C:\Users\ao\AppData\Roaming\npm\node_modules\gulp-cli\node_modules\liftoff\index.js:201:12)
Скорее всего Вы пытаетесь использовать синтаксис ES2015+ и не установили babel или он работает но с ошибкой.
Здесь два выхода — разобраться и настроить либо перейти к старому синтаксису с require
5
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {«os»:»darwin»,»arch»:»any»} (current: {«os»:»win32″,»arch»:»x64″})
Use latest JavaScript version in your gulpfile
Most new versions of node support most features that Babel provides, except the / syntax. When only that syntax is desired, rename to , install the module, and skip the Babel portion below.
Node already supports a lot of ES2015+ features, but to avoid compatibility problems we suggest to install Babel and rename your to .
npm install --save-dev @babel/register @babel/core @babel/preset-env
Then create a .babelrc file with the preset configuration.
{"presets""@babel/preset-env"}
And here’s the same sample from above written in ES2015+.
importgulpfrom'gulp';importlessfrom'gulp-less';importbabelfrom'gulp-babel';importconcatfrom'gulp-concat';importuglifyfrom'gulp-uglify';importrenamefrom'gulp-rename';importcleanCSSfrom'gulp-clean-css';importdelfrom'del';constpaths={ styles{ src'src/styles/**/*.less', dest'assets/styles/'}, scripts{ src'src/scripts/**/*.js', dest'assets/scripts/'}};exportconstclean=()=>del('assets');exportfunctionstyles(){returngulp.src(paths.styles.src).pipe(less()).pipe(cleanCSS()).pipe(rename({ basename'main', suffix'.min'})).pipe(gulp.dest(paths.styles.dest));}exportfunctionscripts(){returngulp.src(paths.scripts.src,{ sourcemapstrue}).pipe(babel()).pipe(uglify()).pipe(concat('main.min.js')).pipe(gulp.dest(paths.scripts.dest));}functionwatchFiles(){gulp.watch(paths.scripts.src, scripts);gulp.watch(paths.styles.src, styles);}export{watchFilesaswatch};constbuild=gulp.series(clean,gulp.parallel(styles, scripts));exportdefaultbuild;
Создание проекта
Двигаемся дальше. Теперь создайте папку проекта в удобном месте вашего компьютера. Назовем ее, например, gproject.
Перейдем в папку проекта и запустим консоль команд для данного каталога. Наиболее быстрый вариант сделать это зажать клавишу «Shift» и удерживая ее щелкнуть правой кнопкой мыши на пустой области окна каталога. Откроется контекстное меню, в котором выбираем «Открываем окно PowerShell здесь«. Данный пункт может называться и по другому — «Открыть окно команд«.

Запускаем инициализацию проекта командой:
Заполняем необходимые поля проекта по шагам и желательно латиницей. После ввода названия жмем Enter и переходим с следующему шагу.
- package-name: вводим название проекта маленькими буквами
- version: оставляем по умолчанию — 1.0.0
- description: вводим описание проекта, например, My first gulp project.
- entry point: (index.js), test command:, git repository:, keywords: — данные шаги оставляем по умолчанию, жмем Enter и переходим к следующему шагу
- author: впишите имя автора, я ввел Zaur Magomedov
- license: оставляем по умолчанию
- Is this ok? — вводим «yes» и жмем Enter поле чего в папке нашего проекта появится файл package.json.

Файл package.json содержит в себе информацию о проекте + информацию об установленных пакетах (плагинов). Это своего рода файл манифеста. Теперь давайте установим Gulp локально в папку нашего проекта. Для этого пишем следующую команду:
флаг —save-dev как раз говорит установщику установить gulp локально в папку нашего проекта.
При установке gulp название пакета и его версия автоматически пропишутся в файле package.json. Вообще такой подход позволяет сохранять файл package.json со всеми установленными пакетами (зависимости), а при разворачивании нового проекта достаточно скопировать данный файл и запустить команду установки в консоли проекта — и все пакеты в проект установятся автоматически. Сейчас может вам будет не совсем понятно, но дальше я уверен вы поймете.
И так, после установки gulp в папке проекта должна появиться папка node_modules, она содержит в себе необходимые зависимости. Также все новые установленные зависимости, прописываемые в package.json будут складываться именно в данную папку. Так что ничего не трогайте в ней и не удаляйте. Не пугайтесь если увидите в ней много файлов и папок.
Давайте откроем файл package.json реактором кода и взглянем на его содержимое.
Мы видим всю ту информацию, которую вводили при инициализации проекта + ниже в блоке «devDependencies» указаны установленные зависимости и их версии. В данном случае это gulp версии 3.9.1. Как я и говорил установилась локально именно та версия, что стоит глобально.
Sample gulpfile.js
This file will give you a taste of what gulp does.
var gulp =require('gulp');var less =require('gulp-less');var babel =require('gulp-babel');var concat =require('gulp-concat');var uglify =require('gulp-uglify');var rename =require('gulp-rename');var cleanCSS =require('gulp-clean-css');var del =require('del');var paths ={ styles{ src'src/styles/**/*.less', dest'assets/styles/'}, scripts{ src'src/scripts/**/*.js', dest'assets/scripts/'}};functionclean(){returndel('assets');}functionstyles(){returngulp.src(paths.styles.src).pipe(less()).pipe(cleanCSS()).pipe(rename({ basename'main', suffix'.min'})).pipe(gulp.dest(paths.styles.dest));}functionscripts(){returngulp.src(paths.scripts.src,{ sourcemapstrue}).pipe(babel()).pipe(uglify()).pipe(concat('main.min.js')).pipe(gulp.dest(paths.scripts.dest));}functionwatch(){gulp.watch(paths.scripts.src, scripts);gulp.watch(paths.styles.src, styles);}exports.clean= clean;exports.styles= styles;exports.scripts= scripts;exports.watch= watch;var build =gulp.series(clean,gulp.parallel(styles, scripts));gulp.task('build', build);gulp.task('default', build);
Release History
- 1.5.0 — Update webpack to 1.9.x (@nmccready). Update other dependencies.
- 1.4.0 — Update webpack to 1.8.x (@Zolmeister).
- 1.3.2 — Fix another place with ? in name (@raphaelluchini).
- 1.3.1 — Fix for paths with ? in their name (@raphaelluchini).
- 1.3.0 — Updating to webpack >= 1.7.
- 1.2.0 — Updating to webpack >= 1.5, vinyl >= 0.4, memory-fs >= 0.2.
- 1.1.2 — Fixes to default stats for logging (@mdreizin).
- 1.1.1 — Add additional stats to default logging (@mdreizin).
- 1.1.0 — Exposes internal webpack if asked via
- 1.0.0 — Support named chunks pipe’d in for multiple entry points.
- 0.4.1 — Fixed regression for multiple entry point support.
- 0.4.0 — Display an error message if there are no input files (@3onyc). Add message on why task is not finishing, Add ability to track compilation progress, Add ability to configure stats output via options (@kompot). Bump webpack version (@koistya).
- 0.3.0 — Update deps (@kompot). Fixes to determining entry (@btipling and @abergs).
- 0.2.0 — Support for mode (@ampedandwired).
- 0.1.0 — Initial release
Gulp
Gulp is a Node task runner. It is a streaming build system in
front-end web development. It helps automate such tasks as copying files,
linting, unit testing, image manipulation, minifying JavaScript and CSS code,
or compiling TypeScript to JavaScript. Gulp is platform independent. In
addition to Node.js, Gulp is used in .NET, Java, or PHP platforms.
Gulp favours code over configuration. It uses tasks to define its workflow. The
tasks are written in the file. Gulp tasks use plugins,
which are small, single-purpose code units. The Gulp ecosystem includes more
than 3500 such plugins. For instance, the plugin minifies
JS files.
Gulp is based on Node streams. It reads data from a filesystem and passes
them through pipelines to transform them. The data goes from one plugin
to another with the use of the function. One task is
performed at a time. Using plugins in the pipeline allows to perform
complex tasks. The original data may be modified, or we can create new
modified copy of the data.
The function creates the stream of source files to perform
the pipe operations on. The specifies where to output the
files once the task is completed.
Установка Gulp
Установку Gulp я буду показывать на примере ОС Windows 10 x64 последней сборки, так как я работаю именно в данной системе.
Первым делом нам необходимо установить node.js. Данный пакет превращает клиентский язык javaScript в серверный. Для тех, кто не знает язык javaScript интерпретирует браузер пользователя. Кстати, Gulp создан на языке javaScript и если вы знакомы с данным языком, то освоить его вам будет намного легче.
Для установки node.js необходимо скачать инсталлятор с официального сайта. Качаем последнюю стабильную версию. Пакет устанавливается как обычная программа и ничего сложного в этом нет.
После установки node.js можно проверить правильно ли все установилось. Открываем консольное окно (командная строка) — в ОС Windows это комбинация клавиш . Вводим команду:
Если все правильно установили в ответ вы увидите версию установленного пакета.

Все, можно приступать к установке Gulp.
Пишем команду для установки Gulp:
Давайте разберем, что значит данная запись:
- npm — говорит о том, что мы запускаем пакет менеджер, который установит Gulp;
- i — это сокращенная запись install, т.е. установить;
- gulp — имя устанавливаемого пакета;
- -g — данный флаг говорит о том, что мы устанавливаем Gulp глобально в систему. Без данного ключа gulp установится в ту папку, из которой запускается команда. Так что имейте это ввиду.
Установка не занимает много времени, примерно 1-2 мин. После завершения работы установщика галп можно проверить корректность установки, также, как и node.js:
Если все правильно, то выдаст версию установленного галп.

Шаг 7: Пожинаем плоды!
Другие плагины, которые могут быть полезны:
- gulp-load-plugins: загружает все модули плагинов Gulp автоматически;
- gulp-preprocess: простой препроцессор HTML и JavaScript;
- gulp-less: плагин препроцессора Less CSS;
- gulp-stylus: плагин препроцессора Stylus CSS;
- gulp-size: отображает размеры файлов;
- gulp-nodemon: использует nodemon для автоматического перезапуска приложений Node.js при их изменении.
Таски Gulp могут запускать любой JavaScript- код или модули Node.js. Они не обязательно должны быть плагинами. Например:
- browser-sync: автоматически перезагружает ресурсы, когда происходят изменения;
- del: удаляет файлы и папки (может очищать папку build в начале каждого запуска).
Преимущества Gulp:
- множество плагинов;
- конфигурация с использованием pipe легко читаема и понятна;
- js можно адаптировать для использования в других проектах;
- упрощает развертывание;
Полезные ссылки:
- домашняя страница Gulp;
- плагины Gulp;
- домашняя страница npm.
После применения описанных выше процессов к простому сайту его общий вес уменьшился более чем на 50%.
Что такое Gulp.js? Gulp – это отличный вариант для автоматического запуска заданий и упрощения процесса разработки.
What’s new in 4.0?!
- The task system was rewritten from the ground-up, allowing task composition using and methods
- The watcher was updated, now using chokidar (no more need for gulp-watch!), with feature parity to our task system
- First-class support was added for incremental builds using
- A method was exposed to create symlinks instead of copying files
- Built-in support for sourcemaps was added — the gulp-sourcemaps plugin is no longer necessary!
- Task registration of exported functions — using node or ES exports — is now recommended
- Custom registries were designed, allowing for shared tasks or augmented functionality
- Stream implementations were improved, allowing for better conditional and phased builds
Usage
1: Conditionally filter content
Condition
var gulpif =require('gulp-if');var uglify =require('gulp-uglify');var condition =true;gulp.task('task',function(){gulp.src('./src/*.js').pipe(gulpif(condition,uglify())).pipe(gulp.dest('./dist/'));});
Only uglify the content if the condition is true, but send all the files to the dist folder
2: Ternary filter
Ternary
var gulpif =require('gulp-if');var uglify =require('gulp-uglify');var beautify =require('gulp-beautify');varcondition=function(file){returntrue;}gulp.task('task',function(){gulp.src('./src/*.js').pipe(gulpif(condition,uglify(),beautify())).pipe(gulp.dest('./dist/'));});
If condition returns true, uglify else beautify, then send everything to the dist folder
3: Remove things from the stream
Remove from here on
var gulpIgnore =require('gulp-ignore');var uglify =require('gulp-uglify');var jshint =require('gulp-jshint');var condition ='./gulpfile.js';gulp.task('task',function(){gulp.src('./*.js').pipe(jshint()).pipe(gulpIgnore.exclude(condition)).pipe(uglify()).pipe(gulp.dest('./dist/'));});
Run JSHint on everything, remove gulpfile from the stream, then uglify and write everything else.
4: Exclude things from the stream
Exclude things from entering the stream
var uglify =require('gulp-uglify');gulp.task('task',function(){gulp.src('./*.js','!./node_modules/**').pipe(uglify()).pipe(gulp.dest('./dist/'));});
Grab all JavaScript files that aren’t in the node_modules folder, uglify them, and write them.
This is fastest because nothing in node_modules ever leaves
Шаг 1: установите Node.js
Node.js можно загрузить для Windows, macOS и Linux с nodejs.org/download/. Доступны различные варианты платформы для установки из бинарных файлов, модульных сборщиков и Docker-образов.
Примечание: Node.js и Gulp работают в Windows, но некоторые плагины могут работать некорректно, если они зависят от собственных бинарных файлов Linux. Одним из вариантов решения проблемы в Windows 10 является подсистема Windows для Linux.
После установки запустите командную строку и введите следующую команду. Она позволит узнать номер версии:
node -v
Вскоре вы станете активно использовать npm – менеджер пакетов Node.js, который необходим для установки модулей. Узнайте номер его версии:
npm –v
Примечание: модули Node.js можно устанавливать глобально, чтобы они были доступны во всей ОС. Но большинство пользователей не будут иметь права на запись в глобальные библиотеки, если у команд npm не будет префикса sudo. Существует несколько вариантов, как исправить разрешения npm. Но можно изменить каталог по умолчанию. Например, в Ubuntu/Debian:
cd ~ mkdir .node_modules_global npm config set prefix=$HOME/.node_modules_global npm install npm -g
Затем добавьте следующую строку в конце ~/.bashrc:
export PATH="$HOME/.node_modules_global/bin:$PATH"
Снова обновите:
source ~/.bashrc
Incremental Builds
You can filter out unchanged files between runs of a task using
the function’s option and :
constpaths={... images{ src'src/images/**/*.{jpg,jpeg,png}', dest'build/img/'}}functionimages(){returngulp.src(paths.images.src,{sincegulp.lastRun(images)}).pipe(imagemin({optimizationLevel5})).pipe(gulp.dest(paths.images.dest));}functionwatch(){gulp.watch(paths.images.src, images);}
Task run times are saved in memory and are lost when gulp exits. It will only
save time during the task when running the task
for a second time.
If you want to compare modification time between files instead, we recommend these plugins:
functionimages(){var dest ='build/img';returngulp.src(paths.images).pipe(newer(dest)).pipe(imagemin({optimizationLevel5})).pipe(gulp.dest(dest));}
If you can’t simply filter out unchanged files, but need them in a later phase
of the stream, we recommend these plugins:
functionscripts(){returngulp.src(scriptsGlob).pipe(cache('scripts')).pipe(header('(function () {')).pipe(footer('})();')).pipe(remember('scripts')).pipe(concat('app.js')).pipe(gulp.dest('public/'))}
Incremental Builds
You can filter out unchanged files between runs of a task using
the function’s option and :
constpaths={... images{ src'src/images/**/*.{jpg,jpeg,png}', dest'build/img/'}}functionimages(){returngulp.src(paths.images.src,{sincegulp.lastRun(images)}).pipe(imagemin({optimizationLevel5})).pipe(gulp.dest(paths.images.dest));}functionwatch(){gulp.watch(paths.images.src, images);}
Task run times are saved in memory and are lost when gulp exits. It will only
save time during the task when running the task
for a second time.
If you want to compare modification time between files instead, we recommend these plugins:
functionimages(){var dest ='build/img';returngulp.src(paths.images).pipe(newer(dest)).pipe(imagemin({optimizationLevel5})).pipe(gulp.dest(dest));}
If you can’t simply filter out unchanged files, but need them in a later phase
of the stream, we recommend these plugins:
functionscripts(){returngulp.src(scriptsGlob).pipe(cache('scripts')).pipe(header('(function () {')).pipe(footer('})();')).pipe(remember('scripts')).pipe(concat('app.js')).pipe(gulp.dest('public/'))}
Use latest JavaScript version in your gulpfile
Node already supports a lot of ES2015, to avoid compatibility problem we suggest to install Babel and rename your as .
npm install --save-dev babel-register babel-preset-es2015
Then create a .babelrc file with the preset configuration.
{"presets""es2015"}
And here’s the same sample from above written in ES2015.
importgulpfrom'gulp';importlessfrom'gulp-less';importbabelfrom'gulp-babel';importconcatfrom'gulp-concat';importuglifyfrom'gulp-uglify';importrenamefrom'gulp-rename';importcleanCSSfrom'gulp-clean-css';importdelfrom'del';constpaths={ styles{ src'src/styles/**/*.less', dest'assets/styles/'}, scripts{ src'src/scripts/**/*.js', dest'assets/scripts/'}};exportconstclean=()=>del('assets');exportfunctionstyles(){returngulp.src(paths.styles.src).pipe(less()).pipe(cleanCSS()).pipe(rename({ basename'main', suffix'.min'})).pipe(gulp.dest(paths.styles.dest));}exportfunctionscripts(){returngulp.src(paths.scripts.src,{ sourcemapstrue}).pipe(babel()).pipe(uglify()).pipe(concat('main.min.js')).pipe(gulp.dest(paths.scripts.dest));}functionwatchFiles(){gulp.watch(paths.scripts.src, scripts);gulp.watch(paths.styles.src, styles);}export{watchFilesaswatch};constclean=gulp.series(clean,gulp.parallel(styles, scripts));gulp.task('clean', clean);exportdefaultbuild;
Issues
If you have a feature request/question how Sass works/concerns on how your Sass gets compiled/errors in your compiling, it’s likely a Dart Sass or LibSass issue and you should file your issue with one of those projects.
If you’re having problems with the options you’re passing in, it’s likely a Dart Sass or Node Sass issue and you should file your issue with one of those projects.
We may, in the course of resolving issues, direct you to one of these other projects. If we do so, please follow up by searching that project’s issue queue (both open and closed) for your problem and, if it doesn’t exist, filing an issue with them.
Отслеживание файлов
Gulp имеет возможность следить за изменением файлов и выполнять задачу или задачи при обнаружении изменений. Эта функция удивительно полезна (для меня, наверное, одна из самых полезных в Gulp). Вы можете сохранить Less-файл, а Gulp превратит его в CSS и обновит браузер без каких-либо действий с вашей стороны.
Для слежения за файлом или файлами используйте функцию gulp.watch(), которая принимает шаблон файлов или их массив (такой как gulp.src()), либо массив задач для их запуска или выполнения функции обратного вызова.
Предположим, что у нас есть задача build, она превращает наши файлы шаблонов в HTML и мы хотим определить задачу watch, которая отслеживает изменение шаблонов и запускает задачу для преобразования их в HTML. Мы можем использовать функцию watch следующим образом:
Теперь при изменении файла шаблона будет запущена задача build, которая создаст HTML.
Вы также можете указать для watch функцию обратного вызова вместо массива задач. В этом случае функция получает объект event содержащий информацию о событии, которое вызвало функцию:
Другой отличительной особенностью gulp.watch() является то, что она возвращает watcher. Используйте его для прослушивания дополнительных событий или для добавления файлов в watch. Например, чтобы одновременно запустить список задач и вызвать функцию, вы можете добавить слушателя в событие change при возвращении watcher:
В дополнение к событию change вы можете прослушивать ряд других событий:
- end
Срабатывает, когда watcher завершается (это означает, что задачи и функции обратного вызова не будут больше вызываться при изменении файлов).
- error
Срабатывает, когда происходит ошибка.
- ready
Срабатывает, когда файлы были найдены и готовы к отслеживанию.
- nomatch
Срабатывает, когда запросу не соответствует ни один файл.
Объект watcher также содержит некоторые методы, которые можно вызывать:
- watcher.end()
Останавливает watcher (при этом задачи или функции обратных вызовов не будут больше вызываться).
- watcher.files()
Возвращает список файлов за которыми следит watcher.
- watcher.add(glob)
Добавляет файлы в watcher, которые соответствуют указанному шаблону glob (также принимает необязательную функцию обратного вызова в качестве второго аргумента). - watcher.remove(filepath)
Удаляет определённый файл из watcher.
Gulp