How can I achieve the function of // @codekit-prepend "" with gulp?

I have recently started using gulp and I am familiar with codekit where I used to write

 // @codekit-prepend "foo.js"
 // @codekit-prepend "bar.js"

to concatenate js files.

Can someone guide me on how to achieve the same result with gulp?

Below is the gulpfile I have been working on:

//*********** IMPORTS *****************
var gulp = require('gulp');
var less = require('gulp-less');
var gutil = require('gulp-util');
var rename = require("gulp-rename");
var map = require("map-stream");
var livereload = require("gulp-livereload");
var concat = require("gulp-concat");
var uglify = require('gulp-uglify');
var watch = require("gulp-watch");
var minifyHTML = require('gulp-minify-html');
global.errorMessage = '';

//Configuration - Change me
var lessFiles = [
    {
        watch: 'source/less/*.less',
        less: 'source/less/master.less',
        output: 'build/css/',
        name: 'all.css',
    }
];
var jsFiles = [
    {
        watch: 'spurce/js/*.js',
        output: 'build/js/',
        name: 'all.js',
        nameMin: 'all.min.js',
    }
];
var htmlFiles = [
    {
        watch: 'source/*.html',
        output: 'build/',
    }
];
//END configuration


gulp.task('watch', function () {
    for (var i in lessFiles) {
        lessWatch(lessFiles[i]);
    }


    for (var j in jsFiles) {
        scriptWatch(jsFiles[j]);
    }

    for (var k in htmlFiles) {
        htmlWatch(htmlFiles[k]);
    }

});

function htmlWatch (htmlData) {
    var opts = {comments:false,spare:true};

    gulp.src(htmlData.watch)
    .pipe(watch(htmlData.watch, function() {
        gulp.src(htmlData.watch)
        .pipe(minifyHTML(opts))
        .pipe(gulp.dest(htmlData.output))
        .pipe(livereload());
    }));
}


function lessWatch(lessData) {
    gulp.src(lessData.watch)
    .pipe(watch(lessData.watch, function() {
        gulp.src(lessData.less)
        .pipe(less(lessOptions))
        .on('error', function(err) {
                gutil.log(err.message);
                gutil.beep();
                global.errorMessage = err.message + " ";
        })
        .pipe(checkErrors())
        .pipe(rename(lessData.name))
        .pipe(gulp.dest(lessData.output))
        .pipe(livereload());
    }));
}

function scriptWatch(jsData) {
    gulp.src(jsData.watch)
    .pipe(watch(jsData.watch, function() {
        gulp.src(jsData.watch)
        .pipe(concat(jsData.name))
        .pipe(gulp.dest(jsData.output))
        .pipe(uglify({outSourceMap: false}))
        .pipe(rename(jsData.nameMin))
        .pipe(gulp.dest(jsData.output));
    }));

}

gulp.task('default', ['watch']);

/// Defaults yo
var lessOptions = {
    'style': 'compressed'
};

// Does pretty printing of less errors
var checkErrors = function (obj) {
    function checkErrors(file, callback, errorMessage) {
        if (file.path.indexOf('.less') != -1) {
                file.contents  = new Buffer("\
                    body * { white-space:pre; }\
                    body * { display: none!important; }\
                    body:before {\
                        white-space:pre;\
                        content: '"+ global.errorMessage.replace(/(\\)/gm,"/").replace(/(\r\n|\n|\r)/gm,"\\A") +"';\
                    }\
                    html{background:#ccf!important; }\
                ");
        }
        callback(null, file);
    }
    return map(checkErrors);
};

Answer №1

Check out gulp-imports for the solution you're looking for.

How to use:

//include("bar.js");

Additionally: If you need to handle both modified files and their parent files (those they are imported by), take a look at my fork: gulp-js-inheritance.

Also: For more gulp features inspired by codekit, check out: codekit-gulp.

Answer №2

Sure, I understand. Here's the variant in the gulpfile:

var jsFiles = [
    {
        watch: './source/js/*.js',
        src: ['./source/js/vendor/waypoints.js',
            './source/js/vendor/jquery.smooth-scroll.js',
            './source/js/vendor/hyphenator.min.js',
            './source/js/vendor/picturefill.min.js',
            './source/js/vendor/various.js',
            './source/js/domready.js'],
        dest: 'build/js/',
        name: 'all.js',
        nameMin: 'all.min.js',
    }
];

function scriptWatch(jsData) {
    gulp.src(jsData.watch)
    .pipe(watch(jsData.watch, function() {
        gulp.src(jsData.src)
        .pipe(concat(jsData.name))
        .pipe(gulp.dest(jsData.dest))
        .pipe(uglify({outSourceMap: false}))
        .pipe(rename(jsData.nameMin))
        .pipe(gulp.dest(jsData.dest));
    }));

}

gulp.task('watch', function () {

    for (var j in jsFiles) {
        scriptWatch(jsFiles[j]);
    }

});

Another way to do it, similar to codekit/prepros style, would be to use gulp-include: https://www.npmjs.org/package/gulp-include

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Vue with Webpack: Do not include any extra properties in the options

While I was in the process of updating npm packages, an error occurred without any specific details provided. I investigated whether it was related to my webpack configuration, but running webpack without using my configuration did not resolve the issue. ...

What is the best way to add a background image to a div using react?

My images folder contains 2 images. See the code snippet below from App.js: import "./styles.css"; import nf_logo from "./images/netflix_logo.png"; import nf_bg from "./images/netflix_bg.jpg;; const divStyle = { backgroundImag ...

Develop a feature within a standard plugin that allows users to add, remove, or refresh content easily

I have developed a simple plugin that builds tables: ; (function ($, window, document, undefined) { // Define the plugin name and default options var pluginName = "tableBuilder", defaults = { }; // Plugin constructor func ...

Use .load() to set an image as background in the div

There is a block of code that is supposed to display images in a div with the class "img", but it isn't functioning correctly. Can you provide some guidance on how to fix this issue? <div class="other"><a href="/index1.html">Link1</a&g ...

Struggling to accurately convert the string into a date object

I have an array of objects structured like this: const days = [ { _id: 12312323, date : '30/12/2021', dateStatus : 'presence' }, ... ] I am looking to convert the date property from a string to a Date object using the follo ...

Exploring Three.js: How to Integrate and Utilize 3D Models

Hey there! I've been doing a lot of research online, but I can't seem to find a solution that works for me. My question is: How can I integrate 3D models like collada, stl, obj, and then manipulate them using commands like model.position.rotation ...

When making a POST request with axios, the req.body object appears to be empty. However, when using the 'request' module, the body is populated as expected

Providing some context - My NodeJS server is running on port 3001 and my React application on port 3000. I've configured a proxy in my React application's package.json to redirect all requests to port 3001 - "proxy": "http://localhost:3001" H ...

The straightforward use of XMLHttpRequest to retrieve the response xhttp.responseText is not functioning properly

I am facing an issue where this.responseText is not returning the content of the file. Can someone assist me in solving this problem? Thank you. Console.log also does not return the content of the file. function loadMegaContent() { var xhttp = new XMLHtt ...

Is it possible for me to create an archive of my GitHub repository even if it is also a published npm module

I am in possession of a GitHub repository for an npm module that I have stopped maintaining. Despite the fact that I have deprecated it on npm, there are still regular weekly downloads occurring. Am I permitted to archive the git repo? ...

Combining Angular JS 1 and Laravel 5.2 for seamless integration

Currently, I am in the process of setting up Angular JS 1 with Laravel 5.2 by installing the necessary dependencies using npm. After installation, a node_modules folder was created alongside the app directory. My primary concern is whether it is recommend ...

The absence of parameters in the Express.js middleware object

const application = express(); let routerInstance = require('express').Router({mergeParams: true}); const payloadMiddlewareFunction = (request, response, next) => { console.log('A:', request.params); const {params, query} = reque ...

Wondering how to execute logic before generating a template in a custom directive?

I am interested in creating a unique custom directive that can take an array of strings and display it as a table. Here is an example of how I envision it: 'string1' | 'string2' | 'string3' | 'string4' 'stri ...

Tips for sending a String[] to my Angular 2 HTML template

In the export class of my component, I have a string array variable declared like this; barChartLabel:string[] = ['2006', '2007', '2008', '2009', '2010', '2011', '2012']; To display t ...

Dealing with Database Timeout in Express JS

I have been trying to extract SQL query execution into a separate file to prevent code repetition, but I am facing timeout issues during execution. var mysql = require('mysql'); const connectionData = { host: 'localhost', user: ...

JavaScript / Ajax / PHP - A Minor Bug That's Bugging Me

I'm in need of some help, as I feel like I'm losing my mind right now. I've developed a code using php/js/ajax to verify if an email address exists when it's submitted. After testing the ajax, I can confirm that the correct values are ...

The array used within the useEffect hook and the getCoordinates function appears to be distinct when printed with console

Utilizing GoogleMap API for Custom Location Display I have an imported array of JSON objects named data which includes an address property. The Google Maps API is used to retrieve coordinates from the addresses in order to generate custom markers displaye ...

Expanding a class functionality by incorporating a method through .prototype

My goal is to define a class called "User" and then add a method to the class using the "prototype" keyword. I want the method "who_auto" to be accessible to all future instances of "User". When testing this code in JSFiddle, I encountered the error messa ...

How many installation packages does Appium require?

Currently, I am in the process of installing the most recent version (1.6.3) of appium using npm. There seems to be an overwhelming number of various packages being downloaded by npm during the installation, and I am uncertain if all of these packages are ...

Enhance the functionality of NodeJS core applications

I recently attempted to modify some custom functions in the FS module of NodeJS, which is an integral part of NodeJS' core modules. The specific file I targeted was fs.js, located in /usr/lib/nodejs. However, despite making changes to the code, I noti ...

Working with HTML5 Canvas to Clip Images

Is there a way to implement a tileset image in canvas like this one? I am trying to figure out how to make it so that clicking on the first tile returns 0, clicking on the tenth tile returns 9, and so on... Any suggestions on how to clip a tileset on an ...