Leveraging Gulp for generating angular $templateCache on a per module/directory basis

Transitioning from grunt to gulp has been a bit challenging for me, especially when it comes to replicating the $templateCache functionality. In my Angular app, I have multiple components/modules with all their necessary resources encapsulated within each module.

With Grunt, I've managed to streamline each module into 5 essential files:

  • module.min.css // concatenated SCSS files
  • module.min.js // concatenated controllers, directives, services
  • module.tpls.min.js // partials in $templateCache
  • module.mocks.min.js // unit test mock objects
  • module.specs.min.js // unit test specs

This modular structure has served me well for years, but the growing complexity of my Grunt file prompted me to explore Gulp as an alternative. The transition has definitely simplified things, but I'm struggling to replicate the template caching functionality.

In my attempts so far, I've encountered plugins that combine all partials into one file, whereas I need to generate a separate template cache file for each module using all HTML files under module/partials/*.html.

In the past, I solved a similar issue in Grunt by looping through directories with grunt.file.expand().forEach() as shown below:

// Example Grunt task to prepare modules
grunt.registerTask('prepModules', '...', function(){

    grunt.file.expand("src/js/modules/*").forEach(function (dir) {

        var mName = dir.substr(dir.lastIndexOf('/') + 1);

        ngtemplates[mName] = {
            module: mName,
            src: dir + "/partials/**/*.html",
            dest: 'dev/modules/' + mName + '/' + mName + '.tpls.min.js'
        };
        grunt.config.set('ngtemplates', ngtemplates);

    });

});

Here's my current Gulp setup for this task:

// Current Gulp task for compiling templates
var compileTemplates = gulp.src('./src/js/modules/**/partials/*.html', {base:'.'})
    .pipe(ngTemplates())
    .pipe(gulp.dest('.'));

While exploring options, none seemed to address my specific requirement of generating individual template cache files per module. Most solutions focused on renaming or relocating files, rather than partitioning based on directory.

I considered using gulp-rename as it worked effectively with CSS compilation:

// Example Gulp task for compiling SCSS
var compileScss = gulp.src('./src/js/modules/**/scss/*.scss', {base:'.'})
    .pipe(sass({includePaths: ['./src/scss']}))
    .pipe(rename(function(path){
        path.dirname = path.dirname.replace(/scss/,'css');
    }))
    .pipe(gulp.dest('.'));

However, when applying rename() after ngTemplates(), only the final output file path is affected rather than individual paths like with sass(). This discrepancy has left me puzzled and seeking suggestions. Any insights would be greatly appreciated!

Answer №1

After searching for a solution to my specific issue, I stumbled upon this helpful post on SO. Although the answer was correct, it didn't show up in my initial searches. Instead of closing my own question, I decided to keep it open to help others who might have similar search terms in mind.

In my quest for a solution, I utilized packages like fs, gulp-ng-templates, and rename to tackle my problem with iterating over directories in Gulp. The code snippet below outlines how I managed to solve this particular challenge:

If you're facing a similar situation or looking to organize tasks per folder in Gulp, you may find this approach insightful. It's akin to following the tasks per folder recipe mentioned here, but with a twist using gulp-ng-templates instead.

Overall, this method reminded me of grunt.file.expand().forEach() in the world of Gulp automation.

Answer №2

When setting up gulp tasks for scss/sass, I prefer to designate a single scss file as the source parameter. This file contains a list of imports, eliminating the need for gulp to concatenate the scss files contents.

//in gulpfile
gulp.src('./src/js/modules/**/scss/main.scss', {base:'.'})

//in main.scss
@import 'a', 'b', 'c';

The 'a', 'b', and 'c' in the import statement would correspond to your other scss files.

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

Is there a way to make the text on my Bootstrap carousel come alive with animation effects?

My website features a Bootstrap Carousel with three elements structured like this: <a><img data-src="img" alt="Third slide" src="img"> </a> <div class="carousel-caption"> <h2> <u ...

The shiny conditional panel fails to evaluate upon initialization

When utilizing conditional panels to dynamically build up my Shiny app, I've noticed that the condition the panel is based on is not initially evaluated. The panel remains visible by default and only becomes hidden after certain actions are taken. Thi ...

Ensure to update the npm package version before making any Git commit

My project is built with Ember using NPM and I utilize Git for version control. I am looking for a way to update or bump the package.json version before or during a Git commit. Is there a method to accomplish this? Should I be implementing Git hooks? ...

AngularJS controller function fails to trigger

I have three directives, "parenta", "parentb", and "childb". The first two are siblings while the third one is a direct child of "parentb". When attempting to call a controller method from "parenta", it does not work. Strangely, calling a method on the "c ...

WebStorm not recognizing NodeJS Core Modules in External Libraries

As a newcomer to NodeJS and WebStorm, I am currently diving into a tutorial on creating an Express app. In the tutorial, the instructor always gets prompted with "Configure NodeJS Core Module Sources" including the URL nodeJS.org when creating a new NodeJ ...

Tips for successfully passing an object with a list property in an ajax request

I have encountered a similar problem to This previous question, but I am struggling to implement the solutions provided. I am unsure of where to include the ModelBinder code mentioned in the responses, so I will explain my issue here. I am working with a s ...

Tips for utilizing New FormData() to convert Array data from an Object for executing the POST request with Axios in ReactJs

When working on the backend, I utilize multer to handle multiple file/image uploads successfully with Postman. However, when trying to implement this in ReactJS on the frontend, I find myself puzzled. Here's a sample case: state = { name: 'pro ...

Ways to separate the strings in angular JS

I'm looking to divide a string into two parts. For instance: www.example.com/page.html?abcdef123456 I want to split the above URL string and save the part that comes after the question mark (?) into a variable. Can anyone advise on how to accomplis ...

Troubleshooting Routing Problems with Stenciljs

In the app-root.txs file of my stenciljs app, I have defined the following routes: <main id="main"> <div class="ba-content-header"> <stencil-router> <stencil-route url="/" component=& ...

Verify whether all the elements within a specific div are distinct by utilizing jQuery

I need to create a select box that, when an option is chosen, generates a certain number of textboxes within a div. Currently, there are three fields: display_name[], user_name[], and user_password[] The code for this functionality is as follows: <se ...

Place a cookie on the alternate language domain

Within my website, we utilize 2 distinct domains, each dedicated to a different language. www.mysite.com en.mysite.com I am interested in implementing JavaScript to establish a cookie on en.mysite.com when clicking a link on www.mysite.com. Here is my ...

Guide on binding Json data dynamically to ACE Editor

I have developed a unique AngularJS application that integrates Ace editor using the UI.Ace directive specifically for handling Json data. This application is designed to generate multiple editors dynamically, each editor containing a Json object within it ...

"Exploring the process of comparing dates using HTML, AngularJS, and Ionic

I am working on an HTML file that shows a list of notification messages. I am trying to figure out how to display the time difference between each notification. The code snippet below displays the notifications and includes the time for each one: <ion- ...

Angular is throwing an error during generation

After manually installing nodejs and npm on my ubuntu 14.04, I checked the versions: root@wemet:~/ang# npm version { http_parser: '1.0', node: '0.10.34', v8: '3.14.5.9', ares: '1.9.0-DEV', uv: '0.10.30', z ...

Is there a way to implement an onclick event on a specific line of text that triggers a popup box only when the text is clicked, without the popup appearing automatically when

I received assistance from a fellow user to customize a popup that turned out great. However, I'm having trouble getting the onclick function to work properly so that the popup only appears when the phone number is clicked. Ideally, I want the phone n ...

Error: Cross-origin request prevented in Chrome due to XMLHttpRequest loading issue

It seems there is a bug specific to Chrome, as this code works without issue in all other browsers. Here's the snippet of code causing the problem: $(function() { $('#content').load('home.html' + '#container').hide( ...

Bootstrap Grid System

I'm currently developing an Image Gallery using Bootstrap, but I've encountered a problem. I am unable to arrange four images in a specific layout - two on top, three below the top ones, and a vertical image in the left corner. Currently, the ver ...

Is the content of the function re-evaluated by setInterval()?

I am currently working on a beginner level single-page application (SPA) using Vue, specifically the Quasar framework. In this application, during the mounted() lifecycle hook, it connects to an MQTT broker to retrieve some information. This information i ...

Combine strings in an array of objects

I have an array containing objects with a "Closed" property that holds numerical values. I want to loop through the array and concatenate all the "Closed" property values found in each object. For example, in the given array, the final result should be 12 ...

adjusting the position of a dynamic JavaScript panel

When trying to make a box slide in from the bottom instead of the top left, I encountered some issues with the code. After altering the CSS position and changing the code that adjusts the position, the sliding effect stopped working. It seems like there mi ...