📜  gulp-wrap (1)

📅  最后修改于: 2023-12-03 14:41:40.113000             🧑  作者: Mango

Gulp-wrap: A Gulp Plugin for Code Wrapping

Gulp-wrap is a Gulp plugin that allows you to wrap your code in various ways. It's perfect for preparing files before concatenation or minification, or for adding boilerplate code to code output.

Installation

To install Gulp-wrap, run the following command:

npm install gulp-wrap --save-dev
Usage

Gulp-wrap is easy to use. You just need to require it in your Gulpfile and use it like any other Gulp plugin.

Wrapping Files

To wrap your files with Gulp-wrap, you can use the wrap method. This method takes a string as its parameter, which specifies the code to wrap your files with.

const gulp = require('gulp');
const wrap = require('gulp-wrap');

gulp.task('wrap', () => {
  gulp.src('src/*.js')
    .pipe(wrap('(function() { <%= contents %> })();'))
    .pipe(gulp.dest('dist'));
});

In this example, we're wrapping our JavaScript files with an IIFE (Immediately Invoked Function Expression).

Conditionally Wrapping Files

Sometimes, you only want to wrap files with specific names or extensions. Gulp-wrap allows you to do this with the condition method. This method takes a function that returns a boolean value, indicating whether to perform the wrapping or not.

const gulp = require('gulp');
const wrap = require('gulp-wrap');

gulp.task('wrap', () => {
  gulp.src('src/**/*.{js,css,html}')
    .pipe(wrap(condition(file => file.extname === '.js'), '(function() { <%= contents %> })();'))
    .pipe(wrap(condition(file => file.extname === '.css'), '/* <%= file.relative %> */\n<%= contents %>'))
    .pipe(wrap(condition(file => file.extname === '.html'), '<html>\n<head>\n<meta charset="UTF-8">\n<title><%= file.relative %></title>\n</head>\n<body>\n<%= contents %>\n</body>\n</html>'))
    .pipe(gulp.dest('dist'));
});

In this example, we're conditionally wrapping files based on their extension. JavaScript files are wrapped with an IIFE, CSS files are wrapped with a comment, and HTML files are wrapped with an HTML template.

Templating

Gulp-wrap also supports templating. You can use any templating engine supported by lodash, such as EJS, Handlebars, or Mustache. Simply pass a second parameter to the wrap method that contains your template.

const gulp = require('gulp');
const wrap = require('gulp-wrap');
const ejs = require('gulp-ejs');

gulp.task('wrap', () => {
  gulp.src('src/*.ejs')
    .pipe(ejs())
    .pipe(wrap('(function() { <%= contents %> })();', '<%= contents %>'))
    .pipe(gulp.dest('dist'));
});

In this example, we're using the gulp-ejs plugin to render our EJS templates, and then we're wrapping the output with an IIFE.

Conclusion

Gulp-wrap is a useful tool for code wrapping in your Gulp workflows. With its simple API and support for templating, it provides a convenient way to transform your code before it's processed by other plugins.