Merging and Reorganizing files using Gulp based on Folder names

In my gulpfile.js, I am attempting to configure a setup that concatenates all .js files located in the src/js folder and names them based on their parent folder.

Here is an example of the folder structure:

project
|
+-assets
| |
| +-app.min.js
| |
| +-vendor.min.js
|
+-src
| |
| +-app
| | |
| | +-file1.js
| | |
| | +-file2.js
| |
| +-vendor
| | |
| | +-file1.js
| | |
| | +-file2.js

While I have been able to set it up for specific folders with designated file names, I am in search of a function that can dynamically handle varying folder structures and names.

Previously, I was using the following configuration:

gulp.task('js', function () {
    gulp.src('src/js/app/**/*.js')
        .pipe(plumber(plumberErrorHandler))
        .pipe(jshint())
        .pipe(jshint.reporter('fail'))
        .pipe(concat('app.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('assets/js'))
});

Answer №1

Check out this official recipe link for a detailed guide on achieving your desired outcome.

function retrieveDirectories(directory) {
    return fs.readdirSync(directory)
      .filter(function(item) {
        return fs.statSync(path.join(directory, item)).isDirectory();
      });
}

var allFolders = retrieveDirectories('src');

allFolders.map(function(currentFolder) {      
      gulp.src(path.join('src', currentFolder, '/**/*.js'))
        .pipe(concat(currentFolder + '.js'))
        .pipe(gulp.dest('assets'));
   });

Answer №2

However, I am searching for a versatile function that can traverse through numerous folders and filenames of varying specifications.

To be honest, I am not aware of a straightforward method to achieve that. In such cases, I often opt to create a path variable containing the names of the folders and structure my task accordingly.

var path = [ 'app', 'vendor' ];

gulp.task('js', function () {
  for (var i = 0; i < path.length; i++) {
    var p = path[i];
    gulp.src('src/' + p + '/**/*.js')
        .pipe(plumber(plumberErrorHandler))
        .pipe(jshint())
        .pipe(jshint.reporter('fail'))
        .pipe(concat(p + '.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('assets/js'))
  }
});

I've come across gulp-path which could potentially meet your requirements, although I have not personally delved into it.

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

Updating a specific array element in MongoDB by its id

I've been attempting this task since yesterday without success. I have two distinct Schemas - the User Schema and the Vital Signs Schema. The Vital Signs Schema is nested inside the User Schema as an array. My goal is to modify a specific vitalSigns ...

Server encountered an unexpected T_STRING error that was not present on the localhost

While my website runs smoothly on localhost, I encounter the unexpected T_STRING error when running it on a workplace server with PHP 5.3.3. The culprit seems to be the exportXML function: eliminating this function resolves the issue. Any suggestions? I&a ...

Troubleshooting code: JavaScript not functioning properly with CSS

I am attempting to create a vertical header using JavaScript, CSS, and HTML. However, I am facing an issue with the header height not dynamically adjusting. I believe there might be an error in how I am calling JSS. Code : <style> table, tr, td, t ...

What is the most effective method for establishing a notification system?

My PHP-based CMS includes internal messaging functionality. While currently I can receive notifications for new messages upon page refresh, I am looking to implement real-time notifications similar to those on Facebook. What would be the most efficient ap ...

Ways to Implement an Origin's First-Party Cookies While Using it as a Third-Party

Imagine I am the owner of a website called "treat1creator.com". I want my clients, who are also website owners, to send HTTP requests to my server that contain cookies I have generated. Here is how it works: User "Sally" visits my site at treat1creator.co ...

Executing a jQuery event after a div's background-image has finished rendering

Greetings and thank you for sparing a moment. I'm curious to know if there exists a method through jQuery to execute a function immediately after a background image in a div has completed downloading and rendering. Imagine you have the following div ...

Steps for instructing Google Maps to identify the location of a provided Google Maps URL

Is it possible to extract longitude and latitude data from a shared URL and place them into a marker? For example, users might copy and paste the 'Share' URL from Google Maps. For instance: or Direct Location: https://www.google.co.nz/maps/plac ...

Error: Attempting to access 'forEach' property on an undefined variable at line 10 in the script file

I'm completely new to Javascript and I apologize for my messy code. I've been struggling with this error for a while now, both on Replit and Visual Studio, but I can't seem to figure it out. Any help would be greatly appreciated! Every time ...

Troubleshooting incompatibility issues between Tailwindcss and NextJS 12 due to experimental features

When I first started using NextJS 12, I decided to try building a project with tailwind. This is my package.json file: { "name": "test", "version": "0.1.0", "private": true, "scripts": { ...

What steps should I take to optimize the performance of this code by implementing rate-limiting for its execution speed?

As I pondered the task at hand, I realized that using a sleep function might be beneficial. However, Javascript lacks a built-in sleep function. How can I tweak this process to avoid hitting a Parse rate-limit? My goal is to execute one (1) Parse.Cloud.ru ...

Express npm dependency fails to start globally

I have recently reinstalled my operating system from Windows 8.1 to Windows 8.1, and I have been using npm for quite some time. Previously, it was working fine as mentioned here. After the reinstallation, I tried installing npm i -g express, but it does n ...

Viewing a PDF within a MUI tooltip

Currently, I am facing an issue where I am attempting to show a preview of a PDF file inside a Material-UI (MUI) Tooltip when a user hovers over a MUI ListItem. While I have successfully displayed previews of PNG and JPG files using Next.js' Image com ...

Is it possible to display a combination of images and text data using JQUERY/AJAX, when the data is sent as objects or arrays?

I'm struggling to figure out how to handle an object or array sent from a server that contains binary picture and text data using JQUERY/AJAX Here is the server-side setup: const url= require('url'), express = require('express&ap ...

Guide on plotting latitude and longitude coordinates on Google Maps with Vue.js through JSON data fetched via AJAX

I have implemented a Vue.js script to fetch JSON data through an AJAX request. However, I am encountering issues with the code. <script> new Vue({ el: '#feed' , data: { details: [], }, mounted() { this.$nextTick(fu ...

Concurrent HTTP Requests - AngularJS

My directive, known as machineForm, includes a dataService: dataService.getMachineTaxesById($scope.machineId).then(function (response) { $scope.machine.machineTaxes = response.data; }); I am using this directive twice simultaneously. <div class= ...

Is there a way to transform a JavaScript array into JSON format in order to use it as the returned data from a RESTful API

Currently, I am exploring how to efficiently convert an array of arrays into a JSON string for retrieval through a RESTful API. On my server, data is fetched from a database in the format: {"user":"some name","age":number ...

Adjust the dimensions of the bootstrap dropdown to match the dimensions of its textbox

The second textbox features a bootstrap dropdown with extensive content that is overflowing and extending to other textboxes below it. I am looking for a way to resize the dropdown to fit the size of its corresponding textbox. UPDATE: I want the dropdown ...

The absence of jasmine-node assertions in promises goes unnoticed

Everything seems to be running smoothly with the code below, except for the assertion part. Whenever I run the test using Jasmine, it reports 0 assertions. Is there a way to include my assertions within promises so they are recognized? it("should open sav ...

Struggling to implement a sidebar in HTML using jQuery and running into issues?

I am struggling to create a template that includes a navbar, sidebar, and other elements that can be used across multiple HTML files. Despite trying different approaches, including changing the jQuery version and downloading jQuery, I am unable to make it ...

Differences between JSX.Element, ReactNode, and ReactElement: When should each be utilized?

Currently in the process of transitioning a React application to TypeScript. Everything seems to be going smoothly, however I've encountered an issue with the return types of my render functions, specifically within my functional components. In the p ...