Processing file names with Gulp

Is there a way to use the filenames retrieved from gulp.src, create in-memory files based on those names, and then pipe that stream to another destination?

For example, I am looking to gather all *.styl files and add each file path to an in-memory file with the prefix @import. Afterwards, I would like to pass this stream to a stylus compiler. Here is what I have in mind:

gulp.src('./src/**/*.styl',{read:false})
.pipe(function(filename){
      return "@import '"+filename+"'"
 })
 .pipe(streamify())
 .pipe(stylus())
 .pipe( gulp.dest('./bin/combined.css'));

I haven't come across any suitable packages for reading and combining stylus files, so I thought of tackling this challenge differently.

I understand that issues may arise related to scoping, style precedence, and specificity rules when merging styles into one file, but it's a necessity for me.

Answer №1

To help out, I have put together a github repository containing the code mentioned. https://github.com/stevelacy/gulp-mix-test

gulpfile.js

var gulp = require('gulp');
var stylus = require('gulp-stylus');
var mixer = require('./mixer');  // a custom gulp plugin we've created


gulp.task('mix', function(){
  gulp.src('./src/**/*.styl')
  .pipe(mixer("outfile"))  // specifying the output file name without extension
  .pipe(stylus())
  .pipe(gulp.dest('./out'));  // setting the output folder
});

In order to maintain clarity in the code, let's create a separate file for our custom gulp plugin.

mixer.js serves as the local gulp plugin responsible for extracting file names and combining them into a Vinyl file that will be passed down the stream to stylus.

mixer.js

var through = require('through2');
var gutil = require('gulp-util');


module.exports = function(outname){
  var paths = '';  // storing the path names with @import

  var write = function (file, enc, cb){
    if (file.path != "undefined"){
      paths =  paths + '\n' + '@import "' + file.path + '"';
    }
    cb();
  };

  var flush = function(cb){  // flush occurs at the end of the concatenation from write()
    gutil.log(gutil.colors.cyan(paths));  // logging it

    var newFile = new gutil.File({  // creating a new file
      base: __dirname,
      cwd: __dirname,
      path: __dirname + '/' + outname + '.styl',
      contents: new Buffer(paths)  // setting the contents to the concatenated paths
    });

    this.push(newFile);  // pushing the new file to gulp's stream
    cb();
  };

  return through.obj(write, flush);  // returning it
};

Upon completion, I am contemplating transforming this into a complete gulp plugin, if necessary.

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 jQuery or Javascript to enclose every character in a given string with an HTML tag

I am trying to create a function that can take a string of text and wrap each letter within that string with an HTML tag such as <i> or <span>. Although I have made some progress, the current solution is not working as expected. The issue I a ...

JavaScript and CSS content, when compared, showcase varying characteristics and functionality

I'm attempting to create a conditional statement based on comparing strings from a CSS content attribute. Here is my current code, but despite the strings being identical, the comparison returns false. CSS .right-section::before { content:" ...

Is it possible to utilize a computed property for dynamically styling a table row based on certain conditions?

I have a table of users that I am currently rendering, and my goal is to highlight the entire row only for the current user. My initial thought was to use a computed property to achieve this, but I seem to be facing some difficulties in making it work. I ...

Retrieve the Multer file name and/or file path

Just checking in on everyone's well-being. I'm currently struggling to retrieve the file path or name after uploading it to the folder. Whenever I try console logging req.files.path or req.files.filenames, it always returns undefined. Could someo ...

Unable to include Authenticated Routes in react router dom

Currently, I am utilizing react-router-dom to manage routing for users who are authenticated and non-authenticated. However, I have encountered an error in Element due to missing properties. Is there a way to make withoutAuth() function properly for authe ...

Tips for launching a colorbox within a specific div container

I am looking to implement a color box that opens without a popup and only shows/hides inside a specific div. Is it possible to target a div to open the colorbox content? <a href='#myGallery' class='group'>click here</a> &l ...

Guide to Rolling a Set of 5 Dice

I am looking to develop a game involving 5 dice. I have already created a function to roll one die using a random method, but I am unsure how to extend this functionality to the remaining four dice without having to create a separate method for each one. ...

Retrieving objects from Firebase in a loop using promises

Seeking guidance on handling promises in AngularJS as a newcomer. Struggling with merging data from two asynchronous arrays into a single array within a for-loop. Encountering a bug where the same picture is displayed for all entries despite different user ...

Having trouble serving compressed files efficiently with Express

I'm running into a problem with serving my gzipped webpack bundle. Whenever I try to serve it, I encounter the dreaded ERR_CONTENT_DECODING_FAILED error on the client-side. Here's a snippet of my middleware setup: `app.get('*.js', func ...

Tips for increasing a cell in AG Grid React table:

Just starting out with the AG Grid library and encountering issues when updating the cells. To simplify, I will describe my problem using basic numbers instead of dates. Start is set to 1. Stop value is already established. End needs to be determined. Dur ...

The edit functionality in jqGrid does not function properly if custom search parameters are designated

Using the Guriddo jqGrid JS version 5.2.0 implemented here: @license Guriddo jqGrid JS - v5.2.0 - 2016-11-27 Copyright(c) 2008, Tony Tomov, [email protected] The code block below showcases an entire self-contained implementation of jqGrid. It inclu ...

Express.js continues to retrieve outdated query results that have already been removed from the database

I am experiencing a strange issue with my PostgreSQL and Express.js setup. Despite updating my database with new entries and deleting old ones, it seems to only display the old data that was deleted days ago. It's almost as if it's stuck in some ...

Retrieve a specific value from a JavaScript object

Utilizing the npm package app-store-scraper, I am extracting the app IDs of 1000 apps from the App Store. My objective is to retrieve the "id" field from each JavaScript object and save it in a .csv file. How can I accomplish this task? Below is the code ...

Ways to conceal an item by considering the size of a different element

I have a question about displaying content within a div element. I want to show a "show more" button only if the content inside the div exceeds a max height of 530px. Otherwise, the button should remain hidden. Here is the code snippet I'm using: Ja ...

Enhance the display in Angular2

Just started working with Angular 2 and I've encountered a problem. I have an API that loads a JavaScript file in my project. The issue is, I need to use this JS file and cannot modify it. Essentially, this JS file has some methods that make AJAX call ...

Tips for extracting data from a JQuery table with Python

My goal is to extract information from the top ten items on a manga website using Python Selenium/BeautifulSoup. However, I am facing challenges due to the website loading its content through a jquery script. The tutorials and guides I have followed do not ...

Having trouble initiating a "curl:localhost:3000" connection, receiving a URI Error message

Recently delving into the realm of node js, I have embarked on a journey to start up a server and experiment with an app designed to trim URLs. However, I find myself at an impasse. Environment: Windows Text Editor: VSCode Below is my code for index.js ...

Encountering the following error: Exceeded maximum call stack size limit

Currently, I am attempting to tackle a specific problem on LeetCode. This particular challenge involves calculating the power of x. However, upon executing my solution, an error message is displayed: RangeError: Maximum call stack size exceeded Here&apos ...

"Implementing a comment system using Node.js and MySQL: A comprehensive guide

Hey there! I have some data that I want to use to create a hierarchical data example. { id_commentForum: 1, id_user: 1, id_thread: 1, comment: 'This is the First Comment', parent: 0, created_at: Wed Jun 22 2016 13:36:38 G ...

Challenge with scroll function in Internet Explorer JavaScript

Here is the code snippet I am working with: var lastScrollTop = 0; window.addEventListener("scroll", function(){ var st = window.pageYOffset || document.documentElement.scrollTop; if (st > lastScrollTop){ $('.sticky').addClass('insi ...