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

Issue with Ionic app causing code execution to hang when the Back Button is pressed

I am currently working on an application using Ionic and React. There is a page in the app where users can upload images from the camera or gallery, which are then saved as binary data in a database (indexed db using Dexie). Everything seems to be function ...

How can we enhance Backbone.sync() at the Model level to include additional parameters?

Currently, I am facing a challenge with overriding Backbone's sync() method for a Model. I have the function signature set up and it is triggered correctly, but I am unsure about what needs to be included in the function body in order for it to automa ...

Is it necessary to have NodeJs in order to host a React app on a server?

I've been working on a .NET Core 2.2 project with React integration, As I'm nearing completion of the project, I have a query that has been on my mind. Do I need Node.js installed on the server for React to function properly? Thank you. ...

Separate .env configurations tailored for development and production environments

Managing different content in my .env files is crucial as I work with both next.js and node.js. The settings vary between development and deployment environments. During development: DOMAIN_URL=https://localhost:3000 GOOGLE_CLIENT_ID='abc' For ...

Tips for obtaining the combined outcome of multiple arrays (3 to 5 arrays) in JavaScript

How can we transform an array of objects with nested arrays into a new array of objects with mixed values? Consider the following input: var all = [ { name: "size", value: [20, 10, 5], }, { name: "color", value: [ ...

How can you access additional fields beyond what is displayed in a dropdown select menu in React?

I am working with an array of Jsons that contain the fields ID, name, and description. My goal is to create a dropdown selection box that will show both the name and description when clicked, and then store the associated ID in the rawID state. I have been ...

tips for creating a jquery/css scales animation

I am looking to implement a unique feature on my website where I create scales with a balancing effect. The scales should mimic an up and down motion continuously. You can see an example of what I'm referring to here Is there a way in jQuery or CSS t ...

Recalling the position of the uploaded image within a v-for loop

I am struggling to solve this issue. Currently, I am utilizing Vue.js in an attempt to construct a dashboard where users can upload up to five images of visitors who are authorized to access a specific service provided by the user. Below is the code snip ...

Is it possible for web browsers to set a timeout on an XmlHttpRequest while it is still active?

When dealing with asynchronous XMLHttpRequests that take a long time to retrieve data from the server, I am searching for a way to abort them. Setting a timeout before sending the XHR is not feasible due to the length of these requests. Although calling X ...

Ending an $.ajax request when the page is exited

Currently, I have a function set on a timer to retrieve data in the background: (function fetchSubPage() { setTimeout(function() { if (count++ < pagelist.length) { loadSubPage(pagelist[count]); fetchSubPage(); ...

Preventing JQuery from interrupting asynchronous initialization

I am currently developing an AngularJS service for a SignalR hub. Below is the factory code for my service: .factory('gameManager', [function () { $.connection.hub.start(); var manager = $.connection.gameManager; return ...

Struggling to center a MatIcon within a MatButtonToggle component in an Angular project

I've been struggling to center the MatIcon in the MatButtonToggle, trying multiple methods without success. It may seem like a minor issue, but it's causing quite a bit of trouble for me. Can someone please guide me on how to make this adjustment ...

Navigating the rollout of a fresh new design

When implementing a new design on a website, how can you bypass the need for users to clear their browser cache in order to see the updated changes? Is there a way to automatically refresh the cache once a new version of the website is uploaded, or are th ...

How can I identify when a CSS transition on a particular element has ended if there are several transitions occurring simultaneously?

In my coding, I have been utilizing the following method to identify when a CSS3 transition has finished: CACHE.previewControlWrap.css({ 'bottom':'-217px' }).one('webkitTransitionEnd transitionend m ...

Trouble with jQuery click event on dynamically generated elements

I have a jQuery function that iterates through each element inside a specified div (#container) and triggers a JavaScript alert whenever a span is clicked. Everything functions correctly when the spans are static. However, when I include code like this: ...

Customize React Hook Form version 7 by incorporating a unique input method for handling empty values

Introducing my custom Input component: export type InputProps = { error?: string } & InputHTMLAttributes<HTMLInputElement> export const Input: FunctionComponent<InputProps> = ({ error, ...props }) => ( <input {...props} /> ) ...

Looking for assistance with overriding kendo UI validation requirements

I'm looking to customize the date validation in my code to validate the date as DD/MM/YYYY. Here's my current code snippet and I'm getting an error message that says: Unable to get property 'methods' of undefined or null referen ...

CSS fixed positioning involves positioning an element relative to the

My website includes a div positioned below the header that contains quick links. I have implemented the solution from http://davidwalsh.name/persistent-header-opacity to ensure this div remains on-screen at all times. However, I would like it to appear a ...

Each loop in the forEach function triggers the mouseup event

I am currently utilizing a foreach loop: objects.forEach(function(object) { var button = '<tr><td>' + object.object.code + '</td><td>' + formatDistance(1456000) + &apos ...

Next.js fails to properly render external links when utilizing the Link component

It was quite surprising to discover that a basic Link component doesn't function as expected in Next.js when attempting to use it with an external URL and HTML Button tag within. Here is my attempt at solving this issue: Attempt 1: <Link href="h ...