### Basic Gulpfile Setup Source: https://github.com/gulpjs/gulp/wiki/gulp-init Place this code in your `gulpfile.js` to set up a default task. Ensure Gulp is installed via npm. ```javascript var gulp = require('gulp'); gulp.task('default', function(){ // place code for your default task here }); ``` -------------------------------- ### Install BrowserSync and Gulp Source: https://github.com/gulpjs/gulp/blob/master/docs/recipes/server-with-livereload-and-css-injection.md Install the necessary development dependencies for BrowserSync and Gulp. ```sh $ npm install --save-dev gulp browser-sync ``` -------------------------------- ### Install BrowserSync Source: https://github.com/gulpjs/gulp/blob/master/docs/recipes/minimal-browsersync-setup-with-gulp4.md Install BrowserSync as a development dependency using npm. ```bash npm install --save-dev browser-sync ``` -------------------------------- ### Install Gulp CLI Source: https://context7.com/gulpjs/gulp/llms.txt Installs the Gulp command-line interface globally. Use this to verify your Gulp installation. ```bash npm install --save-dev gulp ``` ```bash # Verify installation npx gulp --version # CLI version: 3.0.0 # Local version: 5.0.1 ``` -------------------------------- ### Install Gulp, Del, and Vinyl-Paths Source: https://github.com/gulpjs/gulp/blob/master/docs/recipes/delete-files-folder.md Install the necessary packages for Gulp, the 'del' module, and 'vinyl-paths' for pipeline operations. ```sh $ npm install --save-dev gulp del vinyl-paths ``` -------------------------------- ### Gulp Prefixer Plugin Example Source: https://github.com/gulpjs/gulp/blob/master/docs/writing-a-plugin/guidelines.md This example demonstrates a basic Gulp plugin that prepends text to file contents. It handles null files, buffers, and streams, and includes error handling for missing configuration. ```javascript // through2 is a thin wrapper around node transform streams var through = require('through2'); var PluginError = require('plugin-error'); // Consts const PLUGIN_NAME = 'gulp-prefixer'; function prefixStream(prefixText) { var stream = through(); stream.write(prefixText); return stream; } // Plugin level function(dealing with files) function gulpPrefixer(prefixText) { if (!prefixText) { throw new PluginError(PLUGIN_NAME, 'Missing prefix text!'); } prefixText = new Buffer(prefixText); // allocate ahead of time // Creating a stream through which each file will pass return through.obj(function(file, enc, cb) { if (file.isNull()) { // return empty file return cb(null, file); } if (file.isBuffer()) { file.contents = Buffer.concat([prefixText, file.contents]); } if (file.isStream()) { file.contents = file.contents.pipe(prefixStream(prefixText)); } cb(null, file); }); } // Exporting the plugin main function module.exports = gulpPrefixer; ``` -------------------------------- ### Gulpfile: BrowserSync Server Setup Source: https://github.com/gulpjs/gulp/blob/master/docs/recipes/minimal-browsersync-setup-with-gulp4.md Initializes BrowserSync, creates a server instance, and defines tasks for reloading and serving files. ```javascript import browserSync from 'browser-sync'; const server = browserSync.create(); function reload(done) { server.reload(); done(); } function serve(done) { server.init({ server: { baseDir: './' } }); done(); } ``` -------------------------------- ### Install Gulp and Del Source: https://github.com/gulpjs/gulp/blob/master/docs/recipes/delete-files-folder.md Install the necessary packages for Gulp and the 'del' module. ```sh $ npm install --save-dev gulp del ``` -------------------------------- ### Example Gulp Plugin Implementation Source: https://github.com/gulpjs/gulp/wiki/Writing-a-Plugin:-Guidelines This example demonstrates a basic Gulp plugin that prefixes file contents. It handles null, buffer, and stream file types, and includes error handling for missing arguments. It utilizes `through` for stream manipulation and `gulp-util` for `PluginError`. ```javascript var through = require('through'); var gutil = require('gulp-util'); var PluginError = gutil.PluginError; // Consts const PLUGIN_NAME = 'gulp-prefixer'; function prefixStream(prefixText) { var stream = through(); stream.write(prefixText); return stream; } // Plugin level function (dealing with files) function gulpPrefixer(prefixText) { if (!prefixText) { throw PluginError(PLUGIN_NAME, "Missing prefix text!"); } prefixText = new Buffer(prefixText); // allocate ahead of time // Creating a stream through which each file will pass var stream = through(function (file) { if (file.isNull()) return this.queue(file); // Do nothing if no contents if (file.isBuffer()) { file.contents = Buffer.concat([prefixText, file.contents]); return this.queue(file); } if (file.isStream()) { file.contents = file.contents.pipe(prefixStream(prefixText)); return this.queue(file); } }); // returning the file stream return stream; }; // Exporting the plugin main function module.exports = gulpPrefixer; ``` -------------------------------- ### Complete Gulpfile for BrowserSync Setup Source: https://github.com/gulpjs/gulp/blob/master/docs/recipes/minimal-browsersync-setup-with-gulp4.md The complete gulpfile combining all tasks for a minimal BrowserSync setup with Gulp 4. ```javascript import babel from 'gulp-babel'; import concat from 'gulp-concat'; import del from 'del'; import gulp from 'gulp'; import uglify from 'gulp-uglify'; import browserSync from 'browser-sync'; const server = browserSync.create(); const paths = { scripts: { src: 'src/scripts/*.js', dest: 'dist/scripts/' } }; const clean = () => del(['dist']); function scripts() { return gulp.src(paths.scripts.src, { sourcemaps: true }) .pipe(babel()) .pipe(uglify()) .pipe(concat('index.min.js')) .pipe(gulp.dest(paths.scripts.dest)); } function reload(done) { server.reload(); done(); } function serve(done) { server.init({ server: { baseDir: './' } }); done(); } const watch = () => gulp.watch(paths.scripts.src, gulp.series(scripts, reload)); const dev = gulp.series(clean, scripts, serve, watch); export default dev; ``` -------------------------------- ### Install Gulp Package Source: https://github.com/gulpjs/gulp/blob/master/docs/getting-started/1-quick-start.md Install the Gulp package as a development dependency for your project. ```sh npm install --save-dev gulp ``` -------------------------------- ### Install Gulp Handlebars Source: https://github.com/gulpjs/gulp/wiki/Writing-a-Plugin:-README-conventions Install gulp-handlebars as a development dependency using npm. ```shell npm install --save-dev gulp-handlebars ``` -------------------------------- ### Install Gulp CSSLint Source: https://github.com/gulpjs/gulp/wiki/Writing-a-Plugin:-README-conventions Install gulp-csslint as a development dependency using npm. ```shell npm install --save-dev gulp-csslint ``` -------------------------------- ### Install Gulp CLI Globally Source: https://github.com/gulpjs/gulp/blob/master/docs/getting-started/1-quick-start.md Install the Gulp command line utility globally on your system. This allows you to run Gulp commands from anywhere. ```sh npm install --global gulp-cli ``` -------------------------------- ### Install Release Dependencies Source: https://github.com/gulpjs/gulp/blob/master/docs/recipes/automate-releases.md Install the necessary npm packages for automating releases. These include tools for version bumping, changelog generation, and GitHub release creation. ```sh npm install --save-dev conventional-recommended-bump conventional-changelog-cli conventional-github-releaser dotenv execa ``` -------------------------------- ### Running Gulp Task with Arguments Source: https://github.com/gulpjs/gulp/blob/master/docs/recipes/pass-arguments-from-cli.md Example of how to execute the Gulp task defined above, passing a specific environment argument from the command line. ```bash $ gulp scripts --env development ``` -------------------------------- ### Display Task Dependency Tree Output Source: https://github.com/gulpjs/gulp/blob/master/docs/CLI.md Example output of the `gulp -T` command, showing the task names and their descriptions. ```shell [20:58:55] Tasks for ~\exampleProject\gulpfile.js [20:58:55] ├── one [20:58:55] ├── two [20:58:55] ├── three This is the description of task three [20:58:55] ├─┬ four [20:58:55] │ └─┬ [20:58:55] │ ├── one [20:58:55] │ └── two [20:58:55] ├─┬ five [20:58:55] │ └─┬ [20:58:55] │ ├─┬ four [20:58:55] │ │ └─┬ [20:58:55] │ │ ├── one [20:58:55] │ │ └── two [20:58:55] │ └─┬ [20:58:55] │ ├── three [20:58:55] │ └── ``` -------------------------------- ### Gulp CLI Usage Examples Source: https://context7.com/gulpjs/gulp/llms.txt Provides common Gulp command-line interface commands for running tasks, listing tasks with descriptions and dependency trees, and specifying alternative gulpfiles or working directories. ```bash # Run the default task gulp # Run one or more named tasks concurrently gulp styles scripts # List all tasks with descriptions and dependency tree gulp --tasks # [12:00:00] Tasks for ~/project/gulpfile.js # [12:00:00] ├── clean # [12:00:00] ├── styles # [12:00:00] ├─┬ build # [12:00:00] │ └─┬ # [12:00:00] │ ├── clean # [12:00:00] │ └── styles # Plain list of task names (useful for shell scripting) gulp --tasks-simple # Point to a specific gulpfile gulp --gulpfile path/to/gulpfile.js --cwd path/to/project # Silence all logging gulp --silent # Preload a transpiler (e.g., TypeScript support) gulp --preload ts-node/register ``` -------------------------------- ### Using the Gulp Prefixer Plugin Source: https://github.com/gulpjs/gulp/wiki/Writing-a-Plugin:-Dealing-with-Streams Example of how to integrate the gulp-prefixer plugin into a Gulp task. This demonstrates piping files from a source directory through the plugin and then to a destination directory. ```javascript var gulp = require('gulp'); var gulpPrefixer = require('gulp-prefixer'); gulp.src('files/**/*.js') .pipe(gulpPrefixer('prepended string')) .pipe(gulp.dest('/modified-files/')); ``` -------------------------------- ### Usage Example for Gulp Prefix Plugin Source: https://github.com/gulpjs/gulp/blob/master/docs/writing-a-plugin/using-buffers.md Demonstrates how to use the gulp-prefixer plugin in a Gulp task to prepend text to JavaScript files and output them to a different directory. ```javascript var gulp = require('gulp'); var gulpPrefixer = require('gulp-prefixer'); gulp.src('files/**/*.js') .pipe(gulpPrefixer('prepended string')) .pipe(gulp.dest('modified-files')); ``` -------------------------------- ### Common Registry for Sharing Tasks Source: https://github.com/gulpjs/gulp/blob/master/docs/advanced/creating-custom-registries.md An example of a custom registry that shares a 'clean' task, demonstrating how to use `gulpInst.task` within the `init` method. ```javascript const fs = require('fs'); const util = require('util'); const DefaultRegistry = require('undertaker-registry'); const del = require('del'); function CommonRegistry(opts){ DefaultRegistry.call(this); opts = opts || {}; this.buildDir = opts.buildDir || './build'; } util.inherits(CommonRegistry, DefaultRegistry); CommonRegistry.prototype.init = function(gulpInst) { const buildDir = this.buildDir; const exists = fs.existsSync(buildDir); if(exists){ throw new Error('Cannot initialize common tasks. ' + buildDir + ' directory exists.'); } gulpInst.task('clean', function(){ return del([buildDir]); }); } module.exports = CommonRegistry; ``` -------------------------------- ### registry() Usage Source: https://github.com/gulpjs/gulp/blob/master/docs/api/registry.md Example of how to use the registry() function to plug in a custom registry like undertaker-forward-reference. ```APIDOC ## registry() ### Description Allows custom registries to be plugged into the task system, which can provide shared tasks or augmented functionality. ### Signature ```js registry([registryInstance]) ``` ### Parameters #### Path Parameters - **registryInstance** (object) - Required - An instance - not the class - of a custom registry. ### Returns If a `registryInstance` is passed, nothing will be returned. If no arguments are passed, returns the current registry instance. ### Errors #### Incorrect parameter When a constructor (instead of an instance) is passed as `registryInstance`, throws an error with the message: > Custom registries must be instantiated, but it looks like you passed a constructor. #### Missing `get` method When a registry without a `get` method is passed as `registryInstance`, throws an error with the message: > Custom registry must have `get` function. #### Missing `set` method When a registry without a `set` method is passed as `registryInstance`, throws an error with the message: > Custom registry must have `set` function. #### Missing `init` method When a registry without an `init` method is passed as `registryInstance`, throws an error with the message: > Custom registry must have `init` function. #### Missing `tasks` method When a registry without a `tasks` method is passed as `registryInstance`, throws an error with the message: > Custom registry must have `tasks` function. ``` -------------------------------- ### Standard Plugin Pipeline with Gulp Source: https://context7.com/gulpjs/gulp/llms.txt Demonstrates a standard Gulp pipeline using plugins for minification and renaming JavaScript files. Ensure necessary plugins like `gulp-uglify` and `gulp-rename` are installed. ```javascript const { src, dest } = require('gulp'); const gulpif = require('gulp-if'); const uglify = require('gulp-uglify'); const rename = require('gulp-rename'); const through2 = require('through2'); // Standard plugin pipeline function minifyJS() { return src('src/**/*.js') .pipe(uglify()) .pipe(rename({ extname: '.min.js' })) .pipe(dest('dist/')); } // Conditional plugin: only uglify .js files in a mixed pipeline function buildAssets() { return src(['src/**/*.js', 'src/**/*.css']) .pipe(gulpif((file) => file.extname === '.js', uglify())) .pipe(dest('dist/')); } // Inline plugin — no external dependency needed function addHeader() { return src('src/**/*.js') .pipe(through2.obj(function(file, _, cb) { if (file.isBuffer()) { const header = Buffer.from(`/* Built: ${new Date().toISOString()} */\n`); file.contents = Buffer.concat([header, file.contents]); } cb(null, file); })) .pipe(dest('dist/')); } // Use a library directly (no plugin wrapper needed) const { rollup } = require('rollup'); async function bundle() { const build = await rollup({ input: 'src/index.js' }); return build.write({ file: 'dist/bundle.js', format: 'iife' }); } exports.minifyJS = minifyJS; exports.buildAssets = buildAssets; exports.addHeader = addHeader; exports.bundle = bundle; ``` -------------------------------- ### Check Node.js Version Source: https://github.com/gulpjs/gulp/blob/master/docs/getting-started/1-quick-start.md Verify that Node.js is installed and check its version. This is a prerequisite for using Gulp. ```sh node --version ``` -------------------------------- ### Display Simple Task List Output Source: https://github.com/gulpjs/gulp/blob/master/docs/CLI.md Example output of the `gulp --tasks-simple` command, showing a plain list of task names. ```shell one two three four five ``` -------------------------------- ### Verify Gulp Versions Source: https://github.com/gulpjs/gulp/blob/master/docs/getting-started/1-quick-start.md Check the installed versions of the Gulp CLI and the local Gulp package to ensure they are correctly set up. ```sh gulp --version ``` -------------------------------- ### Run Gulp Development Task Source: https://github.com/gulpjs/gulp/blob/master/docs/recipes/minimal-browsersync-setup-with-gulp4.md Executes the default Gulp development task to start the BrowserSync server and watch for changes. ```bash $ gulp ``` -------------------------------- ### Check npm Version Source: https://github.com/gulpjs/gulp/blob/master/docs/getting-started/1-quick-start.md Verify that npm is installed and check its version. npm is used for package management. ```sh npm --version ``` -------------------------------- ### Executing Tasks on Initial Watcher Startup Source: https://github.com/gulpjs/gulp/blob/master/docs/getting-started/8-watching-files.md Set `ignoreInitial` to `false` to ensure tasks are executed immediately when the watcher starts, before any file changes occur. ```javascript const { watch } = require('gulp'); exports.default = function() { // The task will be executed upon startup watch('src/*.js', { ignoreInitial: false }, function(cb) { // body omitted cb(); }); }; ``` -------------------------------- ### watch() Usage Source: https://github.com/gulpjs/gulp/blob/master/docs/api/watch.md Example of how to use the watch() function to monitor JavaScript files and execute a callback when changes are detected. ```APIDOC ## watch() ### Description Allows watching globs and running a task when a change occurs. Tasks are handled uniformly with the rest of the task system. ### Usage ```js const { watch } = require('gulp'); watch(['input/*.js', '!input/something.js'], function(cb) { // body omitted cb(); }); ``` ### Signature ```js watch(globs, [options], [task]) ``` ### Parameters #### globs - **Type**: `string` or `array` - **Required**: Yes - **Description**: Globs to watch on the file system. #### options - **Type**: `object` - **Required**: No - **Description**: Options for the watch function, detailed in the [Options][options-section] section. #### task - **Type**: `function` or `string` - **Required**: No - **Description**: A task function or composed task generated by `series()` and `parallel()`. ### Returns An instance of [chokidar][chokidar-instance-section] for fine-grained control over your watch setup. ### Errors - **Non-string or array with non-strings in `globs`**: Throws an error with the message, "Non-string provided as watch path". - **String or array for `task`**: Throws an error with the message, "watch task has to be a function (optionally generated by using gulp.parallel or gulp.series)". ``` -------------------------------- ### Create Symbolic Links with symlink() Source: https://github.com/gulpjs/gulp/blob/master/docs/api/symlink.md Use this snippet to create symbolic links for files matching a pattern in an output directory. Ensure 'gulp' is installed and imported. ```javascript const { src, symlink } = require('gulp'); function link() { return src('input/*.js') .pipe(symlink('output/')); } exports.link = link; ``` -------------------------------- ### Vinyl File Object Creation and Manipulation Source: https://context7.com/gulpjs/gulp/llms.txt Demonstrates how to create, inspect, and mutate Vinyl objects, which represent files in Gulp pipelines. Includes examples of accessing path properties and cloning files. ```javascript const Vinyl = require('vinyl'); const { Transform } = require('stream'); // Create a Vinyl object manually const file = new Vinyl({ cwd: '/', base: '/project/src/', path: '/project/src/scripts/app.js', contents: Buffer.from('console.log("hello world");'), }); console.log(file.relative); // 'scripts/app.js' console.log(file.dirname); // '/project/src/scripts' console.log(file.basename); // 'app.js' console.log(file.stem); // 'app' console.log(file.extname); // '.js' console.log(file.isBuffer()); // true console.log(file.isNull()); // false // Mutate path properties file.stem = 'app.min'; file.extname = '.js'; console.log(file.path); // '/project/src/scripts/app.min.js' // Clone a Vinyl object (deep clone custom properties by default) const copy = file.clone({ deep: true, contents: true }); // Inline plugin using Vinyl in a Transform stream function prefixComments() { return new Transform({ objectMode: true, transform(file, enc, cb) { if (file.isBuffer()) { const prefixed = '// Auto-generated\n' + file.contents.toString(); file.contents = Buffer.from(prefixed); } cb(null, file); } }); } // Usage: src('src/**/*.js').pipe(prefixComments()).pipe(dest('dist/')) ``` -------------------------------- ### Combine Streams with Ordered Read Streams Source: https://github.com/gulpjs/gulp/blob/master/docs/getting-started/6-explaining-globs.md When ordered glob functionality is needed, use the `ordered-read-streams` library. This example demonstrates combining streams from different file sources before piping them to a destination. ```javascript const order = require("ordered-read-streams"); exports.default = function () { return order([ gulp.src("input/jquery/dist/jquery.js"), gulp.src("input/detect_swipe/jquery.detect_swipe.js"), ]).pipe(gulp.dest('output/')); } ``` -------------------------------- ### Initialize npm Project Source: https://github.com/gulpjs/gulp/blob/master/docs/getting-started/1-quick-start.md Create a package.json file in your project directory. This file manages project metadata and dependencies. ```sh npm init ``` -------------------------------- ### Run Mocha Tests with File Watching using gulp-watch plugin Source: https://github.com/gulpjs/gulp/wiki/Recipes:-Mocha-test-runner-with-gulp Configure Gulp to run Mocha tests and watch for changes in 'lib' and 'test' directories, re-running tests automatically. This example uses the 'gulp-watch' plugin. Install 'gulp', 'gulp-watch', and 'gulp-mocha'. ```javascript // npm i gulp gulp-watch gulp-mocha var gulp = require('gulp'); var mocha = require('gulp-mocha'); var watch = require('gulp-watch'); var gutil = require('gulp-util') gulp.task('mocha', function () { return gulp.src(['test/*.js'], { read: false }) .pipe(mocha({ reporter: 'list' })) .on('error', gutil.log); }); gulp.task('watch', function() { gulp.src(['lib/**', 'test/**'], { read: false }) .pipe(watch(function(events, cb) { gulp.run('mocha', cb); }); }); gulp.task('default', function () { gulp.run('mocha'); gulp.run('watch'); }); // run `gulp watch` or just `gulp` for watching and rerunning tests ``` -------------------------------- ### Integrate Grunt Copy Task in Gulp Source: https://github.com/gulpjs/gulp/blob/master/docs/recipes/run-grunt-tasks-from-gulp.md Configure and run a Grunt copy task within a Gulp task. This example requires Grunt >=1.0.0 and installs `grunt` and `grunt-contrib-copy` as dev dependencies. Note that Grunt tasks are blocking and will prevent other tasks from running until completion. ```javascript // npm install gulp grunt grunt-contrib-copy --save-dev var gulp = require('gulp'); var grunt = require('grunt'); grunt.initConfig({ copy: { main: { src: 'src/*', dest: 'dest/' } } }); grunt.loadNpmTasks('grunt-contrib-copy'); gulp.task('copy', function (done) { grunt.tasks( ['copy:main'], //you can add more grunt tasks in this array {gruntfile: false}, //don't look for a Gruntfile - there is none. :-) function () {done();} ); }); ``` -------------------------------- ### Create Project Directory Source: https://github.com/gulpjs/gulp/blob/master/docs/getting-started/1-quick-start.md Create a new directory for your project using npx mkdirp and navigate into it. ```sh npx mkdirp my-project ``` ```sh cd my-project ``` -------------------------------- ### Sample Gulpfile.js Configuration Source: https://github.com/gulpjs/gulp/blob/master/README.md This Gulpfile demonstrates common tasks like cleaning, processing styles and scripts, and watching for changes. It uses plain functions for tasks and exports them for CLI usage. Ensure all necessary plugins are installed via npm. ```javascript 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/' } }; /* Not all tasks need to use streams, a gulpfile is just another node program * and you can use all packages available on npm, but it must return either a * Promise, a Stream or take a callback and call it */ function clean() { // You can use multiple globbing patterns as you would with `gulp.src`, // for example if you are using del 2.0 or above, return its promise return del([ 'assets' ]); } /* * Define our tasks using plain functions */ function styles() { return gulp.src(paths.styles.src) .pipe(less()) .pipe(cleanCSS()) // pass in options to the stream .pipe(rename({ basename: 'main', suffix: '.min' })) .pipe(gulp.dest(paths.styles.dest)); } function scripts() { return gulp.src(paths.scripts.src, { sourcemaps: true }) .pipe(babel()) .pipe(uglify()) .pipe(concat('main.min.js')) .pipe(gulp.dest(paths.scripts.dest)); } function watch() { gulp.watch(paths.scripts.src, scripts); gulp.watch(paths.styles.src, styles); } /* * Specify if tasks run in series or parallel using `gulp.series` and `gulp.parallel` */ var build = gulp.series(clean, gulp.parallel(styles, scripts)); /* * You can use CommonJS `exports` module notation to declare tasks */ exports.clean = clean; exports.styles = styles; exports.scripts = scripts; exports.watch = watch; exports.build = build; /* * Define default task that can be called by just running `gulp` from cli */ exports.default = build; ``` -------------------------------- ### Gulp Handlebars Usage Example Source: https://github.com/gulpjs/gulp/wiki/Writing-a-Plugin:-README-conventions Example of using the gulp-handlebars plugin in a Gulpfile to compile Handlebars templates. ```javascript var handlebars = require('gulp-handlebars'); gulp.task('templates', function(){ gulp.src(['client/templates/*.hbs']) .pipe(handlebars({ namespace: 'MyApp.templates', outputType: 'hybrid' })) .pipe(concat('templates.js')) .pipe(gulp.dest('build/js/')); }); ``` -------------------------------- ### Using a Shared Common Registry in a Project Source: https://github.com/gulpjs/gulp/blob/master/docs/advanced/creating-custom-registries.md Demonstrates how to import and register a custom registry (like `CommonRegistry`) in a project and then use its tasks. ```javascript const { registry, series, task } = require('gulp'); const CommonRegistry = require('myorg-common-tasks'); registry(new CommonRegistry({ buildDir: '/dist' })); task('build', series('clean', function build(cb) { // do things cb(); })); ``` -------------------------------- ### Gulp CSSLint Usage Example Source: https://github.com/gulpjs/gulp/wiki/Writing-a-Plugin:-README-conventions Example of using the gulp-csslint plugin in a Gulpfile to lint CSS files and report errors. ```javascript var csslint = require('gulp-csslint'); gulp.task('css', function() { gulp.src('./client/css/*.css') .pipe(csslint()) .pipe(csslint.reporter()); }); ``` -------------------------------- ### Bundle Multiple JS Entry Points with Browserify Source: https://github.com/gulpjs/gulp/blob/master/docs/recipes/browserify-multiple-destination.md Use this task to bundle all `.js` files found under the `src/` directory. Each file is treated as an entry point and will be bundled into a separate file in the `dest/` directory. Sourcemaps are generated and the output is minified. ```javascript var gulp = require('gulp'); var browserify = require('browserify'); var log = require('gulplog'); var tap = require('gulp-tap'); var buffer = require('gulp-buffer'); var sourcemaps = require('gulp-sourcemaps'); var uglify = require('gulp-uglify'); gulp.task('js', function () { return gulp.src('src/**/*.js', {read: false}) // no need of reading file because browserify does. // transform file objects using gulp-tap plugin .pipe(tap(function (file) { log.info('bundling ' + file.path); // replace file contents with browserify's bundle stream file.contents = browserify(file.path, {debug: true}).bundle(); })) // transform streaming contents into buffer contents (because gulp-sourcemaps does not support streaming contents) .pipe(buffer()) // load and init sourcemaps .pipe(sourcemaps.init({loadMaps: true})) .pipe(uglify()) // write sourcemaps .pipe(sourcemaps.write('./')) .pipe(gulp.dest('dest')); }); ``` -------------------------------- ### symlink() Usage Source: https://github.com/gulpjs/gulp/blob/master/docs/api/symlink.md Example of how to use the symlink() function in a Gulp pipeline. ```APIDOC ## symlink() ### Description Creates a stream for linking [Vinyl][vinyl-concepts] objects to the file system. ### Method ```js const { src, symlink } = require('gulp'); function link() { return src('input/*.js') .pipe(symlink('output/')); } exports.link = link; ``` ### Signature ```js symlink(directory, [options]) ``` ### Parameters #### directory - **directory** (string | function) - Required - The path of the output directory where symbolic links will be created. If a function is used, the function will be called with each Vinyl object and must return a string directory path. #### options - **options** (object) - Optional - Detailed in [Options][options-section] below. ### Returns A stream that can be used in the middle or at the end of a pipeline to create symbolic links on the file system. Whenever a Vinyl object is passed through the stream, it creates a symbolic link to the original file on the file system at the given directory. Whenever a symbolic link is created on the file system, the Vinyl object will be modified: * The `cwd`, `base`, and `path` properties will be updated to match the created symbolic link. * The `stat` property will be updated to match the symbolic link on the file system. * The `contents` property will be set to `null`. * The `symlink` property will be added or replaced with original path. **Note:** On Windows, directory links are created using junctions by default. The `useJunctions` option disables this behavior. ### Errors - When `directory` is an empty string, throws an error with the message, "Invalid symlink() folder argument. Please specify a non-empty string or a function." - When `directory` is not a string or function, throws an error with the message, "Invalid symlink() folder argument. Please specify a non-empty string or a function." - When `directory` is a function that returns an empty string or `undefined`, emits an error with the message, "Invalid output folder". ### Options **For options that accept a function, the passed function will be called with each Vinyl object and must return a value of another listed type.** | name | type | default | note | |:--------------:|:------:|:-----------:|:--------:| | cwd | string
function | `process.cwd()` | The directory that will be combined with any relative path to form an absolute path. Is ignored for absolute paths. Use to avoid combining `directory` with `path.join()`. | | dirMode | number
function | | The mode used when creating directories. If not set, the process' mode will be used. | | overwrite | boolean
function | true | When true, overwrites existing files with the same path. | | relativeSymlinks | boolean
function | false | When false, any symbolic links created will be absolute.
**Note**: Ignored if a junction is being created, as they must be absolute. | | useJunctions | boolean
function | true | This option is only relevant on Windows and ignored elsewhere. When true, creates directory symbolic link as a junction. Detailed in [Symbolic links on Windows][symbolic-links-section] below. | [options-section]: #options [symbolic-links-section]: #symbolic-links-on-windows [vinyl-concepts]: ../api/concepts.md#vinyl ``` -------------------------------- ### Basic Plugin Usage with Uglify and Rename Source: https://github.com/gulpjs/gulp/blob/master/docs/getting-started/7-using-plugins.md Demonstrates chaining `gulp-uglify` to minify JavaScript files and `gulp-rename` to change the file extension to `.min.js` before saving to the output directory. ```javascript const { src, dest } = require('gulp'); const uglify = require('gulp-uglify'); const rename = require('gulp-rename'); exports.default = function() { return src('src/*.js') // The gulp-uglify plugin won't update the filename .pipe(uglify()) // So use gulp-rename to change the extension .pipe(rename({ extname: '.min.js' })) .pipe(dest('output/')); } ``` -------------------------------- ### lastRun() Usage Example Source: https://github.com/gulpjs/gulp/blob/master/docs/api/last-run.md Demonstrates how to use lastRun() within a Gulp task to enable incremental builds. ```APIDOC ## lastRun() ### Description Retrieves the last time a task was successfully completed during the current running process. Most useful on subsequent task runs while a watcher is running. When combined with `src()`, enables incremental builds to speed up execution times by skipping files that haven't changed since the last successful task completion. ### Usage ```js const { src, dest, lastRun, watch } = require('gulp'); const imagemin = require('gulp-imagemin'); function images() { return src('src/images/**/*.jpg', { since: lastRun(images) }) .pipe(imagemin()) .pipe(dest('build/img/')); } exports.default = function() { watch('src/images/**/*.jpg', images); }; ``` ### Signature ```js lastRun(task, [precision]) ``` ### Parameters #### Path Parameters - **task** (function | string) - Required - The task function or the string alias of a registered task. - **precision** (number) - Optional - Default: `1000` on Node v0.10, `0` on Node v0.12+. Detailed in [Timestamp precision][timestamp-precision-section] section below. ### Returns A timestamp (in milliseconds), matching the last completion time of the task. If the task has not been run or has failed, returns `undefined`. To avoid an invalid state being cached, the returned value will be `undefined` if a task errors. ### Errors When called with a value other than a string or function, throws an error with the message, "Only functions can check lastRun". When called on a non-extensible function and Node is missing WeakMap, throws an error with the message, "Only extensible functions can check lastRun". ## Timestamp precision While there are sensible defaults for the precision of timestamps, they can be rounded using the `precision` parameter. Useful if your file system or Node version has a lossy precision on file time attributes. * `lastRun(someTask)` returns 1426000001111 * `lastRun(someTask, 100)` returns 1426000001100 * `lastRun(someTask, 1000)` returns 1426000001000 A file's [mtime stat][fs-stats-concepts] precision may vary depending on the node version and/or the file system used. | platform | precision | |:-----------:|:------------:| | Node v0.10 | 1000ms | | Node v0.12+ | 1ms | | FAT32 file system | 2000ms | | HFS+ or Ext3 file systems | 1000ms | | NTFS using Node v0.10 | 1s | | NTFS using Node 0.12+ | 100ms | | Ext4 using Node v0.10 | 1000ms | | Ext4 using Node 0.12+ | 1ms | [timestamp-precision-section]: #timestamp-precision [fs-stats-concepts]: ../api/concepts.md#file-system-stats ``` -------------------------------- ### Registering a Custom Registry Instance Source: https://github.com/gulpjs/gulp/blob/master/docs/advanced/creating-custom-registries.md Shows the correct way to register an instantiated custom registry with Gulp, contrasting it with passing the constructor. ```javascript const { registry } = require('gulp'); // ... TestRegistry setup code // good! registry(new TestRegistry()) // bad! registry(TestRegistry()) // This will trigger an error: 'Custom registries must be instantiated, but it looks like you passed a constructor' ``` -------------------------------- ### Check npx Version Source: https://github.com/gulpjs/gulp/blob/master/docs/getting-started/1-quick-start.md Verify that npx is installed and check its version. npx is a package runner tool that comes with npm. ```sh npx --version ``` -------------------------------- ### Gulp Handlebars Namespace Declaration Example Source: https://github.com/gulpjs/gulp/wiki/Writing-a-Plugin:-README-conventions Illustrates how the 'declareNamespace' option in gulp-handlebars generates non-destructive namespace declarations for precompiled templates. ```javascript this["MyApp"] = this["MyApp"] || {}; this["MyApp"]["templates"] = this["MyApp"]["templates"] || {}; this["MyApp"]["templates"]["App"] = this["MyApp"]["templates"]["App"] || {}; this["MyApp"]["templates"]["App"]["Header"] = function () {}; ``` -------------------------------- ### Define Gulp Tasks Source: https://github.com/gulpjs/gulp/blob/master/docs/api/tree.md Define series and parallel tasks for use with Gulp. This example sets up multiple tasks and combines them into more complex sequences. ```javascript const { series, parallel } = require('gulp'); function one(cb) { // body omitted cb(); } function two(cb) { // body omitted cb(); } function three(cb) { // body omitted cb(); } const four = series(one, two); const five = series(four, parallel(three, function(cb) { // Body omitted cb(); }) ); module.exports = { one, two, three, four, five }; ``` -------------------------------- ### Basic File Copy with dest() Source: https://github.com/gulpjs/gulp/blob/master/docs/api/dest.md Use this snippet to copy files from an input directory to an output directory. Ensure Gulp and the src/dest functions are imported. ```javascript const { src, dest } = require('gulp'); function copy() { return src('input/*.js') .pipe(dest('output/')); } exports.copy = copy; ``` -------------------------------- ### Basic File Copy with src() and dest() Source: https://github.com/gulpjs/gulp/blob/master/docs/getting-started/5-working-with-files.md Use `src()` to read files matching a glob pattern and `dest()` to write them to an output directory. Return the stream from the task for async completion. ```javascript const { src, dest } = require('gulp'); exports.default = function() { return src('src/*.js') .pipe(dest('output/')); } ``` -------------------------------- ### Composing Tasks with series() Source: https://github.com/gulpjs/gulp/blob/master/docs/getting-started/3-creating-tasks.md Use `series()` to execute tasks sequentially, one after another. Ensure that each task completes before the next one starts. ```javascript const { series } = require('gulp'); function transpile(cb) { // body omitted cb(); } function bundle(cb) { // body omitted cb(); } exports.build = series(transpile, bundle); ``` -------------------------------- ### Complete Production-Ready Gulpfile Source: https://context7.com/gulpjs/gulp/llms.txt A comprehensive `gulpfile.js` demonstrating a full production build pipeline using modern ES module syntax. It includes cleaning, processing styles (Less, CSS minification), scripts (Babel, Uglify), images (imagemin), watching for file changes, and defining build and development tasks. ```javascript // gulpfile.js — Full production-ready example import { src, dest, watch, series, parallel, lastRun } from 'gulp'; import { deleteAsync } from 'del'; import less from 'gulp-less'; import babel from 'gulp-babel'; import uglify from 'gulp-uglify'; import cleanCSS from 'gulp-clean-css'; import rename from 'gulp-rename'; import imagemin from 'gulp-imagemin'; const paths = { styles: { src: 'src/styles/**/*.less', dest: 'dist/styles/' }, scripts: { src: 'src/scripts/**/*.js', dest: 'dist/scripts/' }, images: { src: 'src/images/**/*.{jpg,png,svg}', dest: 'dist/images/' }, }; export async function clean() { await deleteAsync(['dist/**', '!dist/.gitkeep']); } export function styles() { return src(paths.styles.src, { sourcemaps: true }) .pipe(less()) .pipe(cleanCSS()) .pipe(rename({ suffix: '.min' })) .pipe(dest(paths.styles.dest, { sourcemaps: '.' })); } export function scripts() { return src(paths.scripts.src, { since: lastRun(scripts), sourcemaps: true }) .pipe(babel({ presets: ['@babel/preset-env'] })) .pipe(uglify()) .pipe(rename({ suffix: '.min' })) .pipe(dest(paths.scripts.dest, { sourcemaps: '.' })); } export function images() { return src(paths.images.src, { since: lastRun(images) }) .pipe(imagemin()) .pipe(dest(paths.images.dest)); } export function watchFiles() { watch(paths.styles.src, styles); watch(paths.scripts.src, scripts); watch(paths.images.src, images); } export const build = series(clean, parallel(styles, scripts, images)); export const develop = series(build, watchFiles); export default build; ``` -------------------------------- ### Chokidar Instance Usage Source: https://github.com/gulpjs/gulp/blob/master/docs/api/watch.md Demonstrates how to get a Chokidar instance from Gulp's watch method and attach event listeners for file changes. ```APIDOC ## Chokidar instance The `watch()` method returns the underlying instance of [chokidar][chokidar-external], providing fine-grained control over your watch setup. Most commonly used to register individual event handlers that provide the `path` or `stats` of the changed files. **When using the chokidar instance directly, you will not have access to the task system integrations, including async completion, queueing, and delay.** ```js const { watch } = require('gulp'); const watcher = watch(['input/*.js']); watcher.on('change', function(path, stats) { console.log(`File ${path} was changed`); }); watcher.on('add', function(path, stats) { console.log(`File ${path} was added`); }); watcher.on('unlink', function(path, stats) { console.log(`File ${path} was removed`); }); watcher.close(); ``` ## watcher.on(eventName, eventHandler) Registers `eventHandler` functions to be called when the specified event occurs. ### Parameters #### Path Parameters - **eventName** (string) - Required - The events that may be watched are `'add'`, `'addDir'`, `'change'`, `'unlink'`, `'unlinkDir'`, `'ready'`, `'error'`, or `'all'`. - **eventHandler** (function) - Required - Function to be called when the specified event occurs. Arguments detailed in the table below. ### Arguments for eventHandler - **path** (string) - The path of the file that changed. If the `cwd` option was set, the path will be made relative by removing the `cwd`. - **stats** (object) - An [fs.Stat][fs-stats-concepts] object, but could be `undefined`. If the `alwaysStat` option was set to `true`, `stats` will always be provided. ## watcher.close() Shuts down the file watcher. Once shut down, no more events will be emitted. ## watcher.add(globs) Adds additional globs to an already-running watcher instance. ### Parameters #### Path Parameters - **globs** (string
array) - Required - The additional globs to be watched. ## watcher.unwatch(globs) Removes globs that are being watched, while the watcher continues with the remaining paths. ### Parameters #### Path Parameters - **globs** (string
array) - Required - The globs to be removed. ``` -------------------------------- ### Basic Rollup Usage with Gulp Source: https://github.com/gulpjs/gulp/blob/master/docs/recipes/rollup-with-rollup-stream.md Use this snippet for basic Rollup bundling within a Gulp task. Ensure you have installed gulp, rollup-stream, and vinyl-source-stream. ```javascript // npm install --save-dev gulp @rollup/stream@1 vinyl-source-stream var gulp = require('gulp'); var rollup = require('rollup-stream'); var source = require('vinyl-source-stream'); gulp.task('rollup', function() { return rollup({ input: './src/main.js' }) // give the file the name you want to output with .pipe(source('app.js')) // and output to ./dist/app.js as normal. .pipe(gulp.dest('./dist')); }); ``` -------------------------------- ### Get Task Dependency Tree (Default) Source: https://github.com/gulpjs/gulp/blob/master/docs/api/tree.md Retrieve the basic task dependency tree without deep inspection. This output shows only the top-level tasks. ```javascript { label: 'Tasks', nodes: [ 'one', 'two', 'three', 'four', 'five' ] } ```