Is it possible to selectively process assets based on their type using Gulp and Useref?

Is it possible to selectively process css and js assets using gulp-useref based on the build type specified in the html tags?

<!-- build:<type>(alternate search path) <path> -->
... HTML Markup, list of script / link tags.
<!-- endbuild -->

I am interested in differentiating and applying autoprefixing and jslint only to non-vendor assets by specifying different build types for css and css_vendors like below:

index.html

<!-- build:css_vendors css/vendors.min.css -->
    <link rel="stylesheet" href="vendor/fontawesome/css/font-awesome.css">
    <link rel="stylesheet" href="vendor/magnific-popup/magnific-popup.css">
<!-- endbuild -->
<!-- build:css css/styles.min.css -->
    <link rel="stylesheet" href="css/theme.css">
    <link rel="stylesheet" href="css/custom.css">
<!-- endbuild -->

gulpfile.js

gulp.task('useref', function() {
  return gulp.src('index.html')
    .pipe(useref({
      css: [ autoprefixer(), minifyCss() ],
      css_vendors: [ minifyCss() ]
    }))
    .pipe(gulp.dest('build/'));
});

Unfortunately, the current gulpfile.js implementation is not functioning as expected.

Answer №1

If you're looking for a plugin that works similarly to what you need, you may want to check out gulp-html-replace - although I have limited knowledge of its functionality.

One way to achieve your desired outcome is by using useref with gulp-if to execute a function on a match:

.pipe($.if('*.css', autoprefixer()))

However, it appears that the resources in the source code you're working with may not be enough to meet your requirements, especially if you need to extract assets from an HTML file. Here's an example from one of my tasks:

gulp.task('build-dist', ['wiredep'], function () {

    var assets = $.useref.assets({searchPath: ''});
    var cb = Math.random();

    return gulp
        .src(config.indexFile)
        .pipe($.rename(config.outputIndexFile))
        .pipe($.plumber())
        .pipe(assets)
        .pipe($.if('*.css', $.csso()))
        .pipe($.if('**/lib.js', $.uglify({preserveComments: 'license', mangle: false})))
        .pipe($.if('**/init.js', $.ngAnnotate()))
        .pipe($.if('**/init.js', $.uglify({mangle: false})))
        .pipe($.if('**/app.js', $.ngAnnotate()))
        .pipe($.if('**/app.js', $.uglify()))
        .pipe(assets.restore())
        .pipe($.useref())
        .pipe($.replace('.css"', '.css?cb=' + cb + '"'))
        .pipe($.replace('.js"', '.js?cb=' + cb + '"'))
        .pipe(gulp.dest(config.indexLocation))
        ;
});

Note: The $ symbol is defined as

var $ = require('gulp-load-plugins')({lazy: true});
- this shorthand helps avoid repetitive "require" statements. :)

Answer №2

If you want to achieve this, it seems like the best approach is to utilize gulp-usemin instead of gulp-useref. Here's an example:

index.html

<!-- build:css_vendors css/vendors.min.css -->
    <link rel="stylesheet" href="vendor/fontawesome/css/font-awesome.css">
    <link rel="stylesheet" href="vendor/magnific-popup/magnific-popup.css">
<!-- endbuild -->
<!-- build:css_styles css/styles.min.css -->
    <link rel="stylesheet" href="css/theme.css">
    <link rel="stylesheet" href="css/custom.css">
<!-- endbuild -->

gulpfile.js

gulp.task('usemin', function() {   
   return gulp.src('index.html')
     .pipe(plumber())
     .pipe(usemin({
       css_vendors: [ minifyCss() ],
       css_styles: [ autoprefixer(), minifyCss() ]
     }))
     .pipe(gulp.dest('./dist')); });

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

HighStocks should show categories instead of dates

The zoom function in HighCharts is what drew me to it initially. Everything was working perfectly until I encountered an issue that I can't seem to resolve. Here's my code snippet: http://jsfiddle.net/ma50685a/16/ $(function() { // Crea ...

Determine the total by multiplying the value of a dropdown menu and a text input field using jQuery when the values are changed

I am new to jQuery and JavaScript. I have a textbox and a select box, and when I enter a value in the textbox and select a value from the select box, I want to display the multiplication of both values in another textbox. I have tried doing this with two t ...

Ways to determine the length of a string that includes zero or negative width characters such as u0007 or 

Consider the following scenario: I have a string 'aa\b\u0007\u0007' var myString = 'aa\b\u0007\u0007'; console.log(myString); //=> 'a' (plus 2 beeps) console.log(myString.length); //=> 5 ...

The for...of loop cannot be used with the .for property since it is not iterable. (Is

let arr = [{ category: 'music', views: 20 }, { category: 'abc', views: 32 }, { category: 'bob', views: 20 } ] for (const [key, value] of arr) { console.log(key, value) } console.log(Array ...

What is the best way to allow text input in a table cell to exceed the confines of the table when it is clicked on

I am currently working on a table that has three columns: a label, a dropdown selector, and an input field. The challenge I'm facing is that the input field needs to accommodate multiple lines of content, specifically in JSON format. However, I want ...

Establishing the maximum width of a Vuetify expansion panel component

https://i.sstatic.net/QqKVv.png I'm currently in the process of developing a webpage using vuetify and nuxt. My main focus right now is adjusting the max-width property of the expansion panel UI component (https://vuetifyjs.com/en/components/expansio ...

What is the best way to trigger a jQuery function once a form has been successfully submitted?

Is there a way to execute a jQuery function AFTER a form has been submitted? I am familiar with calling a function ON submit, but I specifically need it to run after the form data has been posted and stored in the database using PHP. In my website projec ...

I need some help with adjusting the number of rows shown per page in MaterialReactTable

I've been utilizing MaterialReactTable and my goal is to display only 5 items on each pagination page. Despite setting muiTablePaginationProps, I still see 10 items per page. How can I resolve this issue? <MaterialReactTable columns={columns} ...

Looking for guidance on restructuring a JSON object?

As I prepare to restructure a vast amount of JSON Object data for an upcoming summer class assignment, I am faced with the challenge of converting it into a more suitable format. Unfortunately, the current state of the data does not align with my requireme ...

Ways to modify input value based on another input in VueJS

Two sets of text boxes are displayed in a grid format, which can be viewed here. The objective is for users to fill out the top boxes and have the values automatically update as they fill out the corresponding bottom boxes. For example, if you input 100 i ...

Is there a way to ensure that the text inside the red div is fully contained within the div, so that when it is expanded, all the text will be displayed properly?

I've been experimenting with creating an interactive function that expands a red box and reveals additional text when the cursor hovers over it, using a vertical linear transition. Unfortunately, I'm facing difficulty in implementing this feature ...

Utilize JavaScript to parse JSON containing multiple object settings

After receiving the server's response, I am looking to extract the "result" from the JSON data provided. This is my JSON Input: { "header":{ "type":"esummary", "version":"0.3" }, "result":{ "28885854":{ "uid":"28885854", "pub ...

Manage multiple sessions at the same time

In a specific scenario, we face the need to manage multiple sessions similar to Google Accounts. Users should be able to add different accounts in separate tabs, each with its own unique content. For example, user1 may be logged in on Tab1 while user2 is l ...

Issue with React when attempting to add a secondary class to Toggle component

Is there a way to add a second class to my <div> with the class "button"? When I try to append 'toggle-button', the class doesn't seem to work. <CSSTransitionGroup transitionName="buttonAninmated" transitionEnterTimeout={30 ...

Tips for accessing a new variable within an array of objects using JavaScript

How can I retrieve a new variable (section) after every 3 objects are called from an array in JavaScript ES6 Map? I've attempted to do this with an ES6 Map, but I'm not achieving the desired result. Can someone please assist me? Thank you! Below ...

Properly segmenting sections into components in Angular

My project has a specific folder structure as shown below: https://i.sstatic.net/7oihC.png In my list-page, I perform operations such as create, update, and delete using modal dialogs. I am considering creating 4 pages for each of these CRUD operations a ...

Sorting columns containing English, Japanese entries, and null values using a customized sorting algorithm in MUI Data Grid is a straightforward process

I am working with an MUI data grid and I am looking to implement a custom sorting algorithm for columns that can override the default options provided by MUI. The data in my fields is in English, Japanese, as well as empty/null values. My desired output sh ...

Finding the location of an "Apply" button on an Angular HTML page

There is an issue with the positioning of the apply button in the filter bar. Sometimes it displays in the next row instead of alongside the other filters. How can I determine the exact position of this apply button within the HTML page? <div class=&quo ...

Steps for connecting an external .otf file in p5.js

I'm struggling to connect a custom font file to my p5.js sketch through a URL in order to upload it on codepen.io. Unfortunately, the font is not available on Google Fonts. I attempted to include the URL in the load font function like this: loadFon ...

What could be causing me to receive no results?

Currently, I am expanding my knowledge in JavaScript, Ajax, and NodeJs. My current project involves creating a webpage that can display a string retrieved from the server. The server-side code is as follows: var express = require('express'); v ...