Utilizing Gulp variables to create dynamic destination file names?

As a newcomer to gulp, I am curious about the feasibility of achieving my desired outcome.

Here is the structure of my projects:

root
|
components
|   |
|   component_1
|   |   styles.scss
|   |   actions.js
|   |   template.html
|   |   ...
|   component_2
|   |   styles.scss
|   |   template.html
|   |   ...
|
public
    |
    assets
         |
         css (destination)
         |    component_1.css
         |    component_2.css
         |    ...
         js (destination)

My goal is for Gulp to save the compiled css files in the corresponding css folder within public/assets, but to use the name of the folder where it found the scss file. Is this achievable? Would I need to utilize a plugin for this task? Thank you! P.S. I understand renaming the scss file could achieve the same result, but I prefer to avoid that route.

Answer №1

Creating dynamic tasks with Gulp is a straightforward process, especially if you require flexibility. Since Gulp is written in pure JavaScript, it allows you to easily craft your own functions. Utilizing the gulp-rename plugin, you can modify parts or the entire file name before storing it.

To kickstart the process, consider the following outline:

var rename = require('gulp-rename'),
    path = require('path'),
    glob = require('glob'); // npm i --save-dev glob    

var components = glob.sync('components/*').map(function(componentDir) {
        return path.basename(componentDir);
    });

components.forEach(function(name) {
    gulp.task(name+'-style', function() {
        return gulp.src('components/'+name+'/styles.scss')
            .pipe(sass()) // etc
            .pipe(rename(name + '.css'))
            .pipe(gulp.dest('public/assets/css'))
    });

    gulp.task(name+'-js', function() {
        // implement similar logic for JS files
    });

    gulp.task(name+'-build', [name+'-style', name+'-js']);
});

// task to build all components
gulp.task('build-components', components.map(function(name){ return name+'-build'; }));

As a result, individual tasks like component_1-build, component_1-style, component_1-js, and so forth will be generated for each component.

In addition, a master task will enable the construction of all components simultaneously.

Answer №2

While this question may be old, I recently found myself delving into this topic and stumbled upon it. If you're looking to add some dynamism to the destination path, here's a helpful tip.

By passing a function as an argument to gulp.dest, you can perform some preprocessing on the destination path like so:

.pipe(gulp.dest(function (file) {
    // file represents the current file in the stream
    // implement your logic here               
    return newPathString;
}));

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

Comprehending the positioning of elements enclosed within a parent <div> tag

I'm struggling to understand why: vertical-align - isn't behaving as expected in this scenario, even though the elements are aligned along a baseline and are inline elements. I've experimented without using float but that didn't sol ...

When executing the gulp watch command, Gulp unexpectedly shuts down instantly

After running 'gulp watch' in my terminal, I received the following output: [13:59:40] Using gulpfile ~/path/to/gulpfile.js [13:59:40] Starting 'watch'... [13:59:40] Finished 'watch' after 45 ms Below is the relevant code s ...

Saving URI from HTTP request in Javascript using Google Drive API: A step-by-step guide

I'm struggling to understand and implement the instructions provided at https://developers.google.com/drive/v3/web/manage-uploads#save-session-uri While I've successfully used javascript to upload files to Google Drive, I am now faced with a cha ...

Pressing the reset button will restore the table to its original

As a new React developer with experience mainly in hooks, I have been struggling to find a good example involving hooks. Currently, I am working on implementing an antd table with search functionality. My question is, when a user types something into the ...

What is the best way to trigger a modal on Bootstrap using a JavaScript/jQuery function?

I encountered an issue while attempting to call a bootstrap modal using a simple button or link, which may be due to a conflict with my select2 plugin (although I am uncertain). I tried appending the button to the select2 dropdown but it doesn't seem ...

Is it feasible to incorporate a third-party JavaScript file into a React application?

I have a JavaScript file from a previous MVC project that generates a basic table using ExtJS. Currently, I'm working on developing a new React application with a navigation bar and sidebar. My goal is to explore the possibility of importing the exis ...

Explore the functionality of the webix grid by clicking on the url column

I've recently created a table in Webix, and I have a column labeled "TBD" where I display a URL. My question is: how can I make this URL, 'https://pops.dra.com/TBD.php?jour=$adep&arc=$ads', clickable? while($row = mysqli_fetch_array($req ...

Tips for selecting an <select> option value based on an URL parameter automatically

I have a 2-step form where I am successfully passing the first name in the URL from step 1 to step 2, but I am struggling to do the same for a select field. Here's an example of what I have: In the URL: ?firstname=Bob Form Field: <input type= ...

Limit the bootstrap datepicker to display only certain dates and today's date

I've integrated the Bootstrap Datepicker into my website. I need to customize it so that only specific dates are enabled, including today's date, and all other years, months, and days are hidden from the Datepicker. How can I achieve this? Furth ...

Eliminating and restoring the background in a form field when it is in focus

/* This function clears the default text in a field when clicked on */ $('#edit-field-activity-notes-und-0-value') .each(function() { $(this).data('default', this.value); var mybackground = $(this).css('backgroun ...

What steps can be taken to design a unique CSS pop-up that triggers upon page load, limited to one appearance per visitor every week

I have the following code snippet that allows me to display a pop-up either by clicking on the link or hovering over it. I am looking to modify it so that the pop-up opens when the page loads and restrict it to open only once per visitor per week. As some ...

When you hover over them, chips transform their color

I am currently using a chip in my code and I would like to change its color when the mouse hovers over it. I attempted to achieve this by using: hover:{ backgroundColor: 'red', } In addition, I incorporated const StyledChip ...

What are the steps for creating a standalone build in nextJS?

Currently, I am undertaking a project in which nextJS was chosen as the client-side tool. However, I am interested in deploying the client as static code on another platform. Upon generating a build, a folder with all the proprietary server elements of ne ...

Unable to navigate to the frame within the Salesforce Lightning interface

Attached below is the screenshot and code that I have used: driver.switchTo().frame(driver.findElement(By.xpath("//iframe[contains(@title,'Deploy Data Set')]"))); <div class="slds-template_iframe slds-card" force-aloha-page_aloha-page=""> ...

Easy fix for 3 circles (images) placed in a row with equal distance between them and perfectly aligned

I've been spending the last 3 days trying to accomplish this specific task: 3 circular images arranged horizontally with equal spacing Occupying 70% of the central screen area Height and width based on percentages for browser resizing adjustment It ...

Conflicting behavior between jQuery focus and blur functions and retrieving the 'variable' parameter via the $_GET method

There is a simple focus/blur functionality here. The default value shown in the 'Name of Venue' input field changes when the user clicks on it (focus) and then clicks away(blur). If there is no text entered, the default value reappears. Input fi ...

Selenium and AngularJS patiently wait before carrying out specific actions

I have been using selenium to test an AngularJS application and I am encountering an issue where I am unable to perform any actions on the page until it is fully loaded. Although I have considered using Thread.sleep(), I am aware that this is not the most ...

Switch the background color of a list item according to a JSON search

Our organization is in need of a feature where members can be inputted into a field and the background color of the parent list item changes based on the name lookup in a JSON file. We are open to a jQuery solution, but JavaScript will also work! You can ...

What could be causing my router UI in angular.js to malfunction?

Having an issue with routing not functioning as intended, here is the relevant code: $urlRouterProvider. otherwise('/list'); $stateProvider. state('home', { abstract: true, views: { 'header': { templateUrl: &apos ...

How to detect a right-click on empty time slots in Fullcalendar agenda views

I am working with a calendar feature on my web application using Adam Shaw's fullcalendar 2.1.1 JS library. I have successfully set up right-click responses for events and days by binding the "mousedown" event in the dayRender and eventRender callback ...