JustinCann
4/6/2018 - 4:45 PM

Concat Vendor Scripts

Node

/*
Combines jQuery and foundation into vendor.js
*/

// ---------------------------------------------------------------------------
// Modules
// ---------------------------------------------------------------------------

import CombinedStream from 'combined-stream';
import chalk from 'chalk';
import fs from 'fs';

// ---------------------------------------------------------------------------
// Constants and Variables
// ---------------------------------------------------------------------------

const jqueryJS = './node_modules/jquery/dist/jquery.js';
const foundationJS = './node_modules/foundation-sites/dist/js/foundation.js';
const combinedStream = CombinedStream.create();

const destinationFolder = './public/js/';
const destinationFile = 'vendor.js';
const log = console.log;

var missingFiles = 0;

// ---------------------------------------------------------------------------

// check for destination folder
if (!fs.existsSync(destinationFolder)){
    fs.mkdirSync(destinationFolder);
}


log(chalk.blue('Checking source files.'));

// iterate through sources files to make sure they are present
[jqueryJS, foundationJS].forEach(function(file) {

    if (fs.existsSync(file)) {
        combinedStream.append(fs.createReadStream(file));
    }
    else {
        log(chalk.yellow(`${file} file is missing.`));
        missingFiles += 1;
    }

});

log(chalk.blue('Creating new file.'));

// create the new file
combinedStream.pipe(fs.createWriteStream(destinationFolder + destinationFile));

// make sure file created successfully
if (fs.existsSync(destinationFolder + destinationFile)) {
    if (missingFiles === 0 ) {
        log(chalk.green('vendor.js created successfully :D'));
    } else {
        log(chalk.yellow('vendor.js created successfully.'));
        log(chalk.yellow(`However there are ${missingFiles} file(s) missing.`));
        log(chalk.yellow('Run ' + chalk.white.underline.bold('npm install') + ' and try again.'));
    }
} else {
    log(chalk.red('vendor.js creation failed :('));
    log(chalk.red("Don't forget to run " + chalk.white.underline.bold('npm install')));
    log(chalk.red("Try again"));
}