Extract SCSS import filepaths using NPM and Gulp

Currently, in my gulp setup, I have several CSS files being produced - a general 'core' one, and then template-specific stylesheets.

Instead of re-compiling all stylesheets with each change, the setup only compiles the necessary ones. However, this has resulted in complex "watch" paths that cover many files reflecting what's in the primary SCSS files for each template (which contain @use/@import statements).

I had an idea: rather than manually writing out all the watch filepaths, why not 'crawl' the SCSS file to automatically grab all the filepaths for any @use/@import statements recursively?

For example, let's take this "blog.scss" file:


    // Variables 
    @import 'variables';
    
    // Tools
    @import './tools';
    
    // Parts
    @import './core/base';
    @import './templates/blog';

Is there a way to extract all the filepaths for its @import statements? Like so:

'local-dev/styles/variables.scss'
'local-dev/styles/tools.scss'
'local-dev/styles/core/base.scss'
'local-dev/styles/templates/blog.scss'

I've thought about fetching the file as a string and using regex, but that wouldn't account for file extensions (.scss/.css/_partials.scss) and could lead to other issues.

Any suggestions or ideas are greatly appreciated.

Thanks in advance!

Answer №1

Incremental build systems are designed to compile only files that have been changed, without affecting anything else.

If you want to dive deeper into this concept, I highly recommend reading the article titled Incremental SASS Builds with Gulp by Sarthak Batra.


For a quick solution, follow these steps:

  1. Ensure you are using gulpJS v4 by checking your project directory with the console command: gulp -v

  2. Install the gulp-dependents plugin using the command: npm i --save-dev gulp-dependents in your project folder.

  3. Add the import statement for

    const dependents = require("gulp-dependents")
    in your gulpfile.js.

  4. Update your gulp styles function to only compile changed files.

function styles(callMeBack) {
  return gulp
    .src(paths.styles.src, { since: gulp.lastRun(styles) })
    .pipe(dependents())
    .pipe(scss())
    .pipe(gulp.dest(paths.styles.dest))
    .pipe(browserSync.stream())
    .on("end", callMeBack)
}
  • path.styles.src refers to the path of your styles folder;
  • since: gulp.lastRun(styles) checks if current files have been changed since the last run;
  • .dependents() performs a deep search to find files dependent on the current one in the pipeline;
  • The .scss() and gulp.dest functions are self-explanatory;
  • Only the styles that were edited will be compiled as a result;
  1. If you have multiple styles functions, consider creating a new one to avoid disrupting your workflow.

P.S Using since.lastRun ensures changes are detected correctly after the first run, following a process of compiling everything initially, waiting for changes, checking changes, and compiling only edited files.

P.P.S Feel free to ask any questions you may have!

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

Encountering a problem while trying to install Gulp

Struggling to get Gulp up and running on my system. When I enter the command "npm install gulp" in the terminal, an error message https://i.sstatic.net/113lC.png keeps popping up. Can someone guide me through the process of installing Gulp? The internet ...

Encountering the error "Module 'aws-sdk', 'child_process', 'net' cannot be resolved" within the /node_modules/watchpack directory when using Webpack

I'm encountering issues while trying to compile my prod webpack file, specifically receiving 5-10 errors related to "cannot resolve module" aws-sdk and child_process. All of these errors seem to point back to the same path: "ERROR in (webpack)/~/watc ...

Encountering a problem with VUE3: npm init due to unexpected token error

Recently initiated the new Vue3 setup (npm init vue@latest) but encountered an error right away: npx: installed 1 in 1.787s C:\neard\tmp\npm-cache\_npx\10696\node_modules\create-vue\outfile.cjs:3896 const isFeature ...

The styles for the React calendar are not being properly applied to the calendar component due to CSS overriding

Having trouble overriding the default Calendar.css file in NextJS while creating a calendar component. Even after adding my own custom styles, they aren't being applied. Deleting the css file contents doesn't change the format either. Only when c ...

How can I make a bootstrap container maximize the available viewport space?

I've come across several similar posts, but none seem to address my particular dilemma. My challenge lies in presenting a table at the end of a bootstrap grid: <div class="container-fluid"> <!-- Various rows with different size ...

Troubleshooting: Broccoli Builder encountered an issue with the `UglifyWriter` plugin while working with an Ember application

For my frontend application, I've been using the Ember framework successfully up until last week. However, when attempting to build the application recently, I encountered the following issue: Build failed. Build Canceled: Broccoli Builder ran into an ...

Is there a way for me to customize the appearance of the Material UI switch component when it is in the checked

I am seeking to customize the color of the switch component based on its checked and unchecked state. By default, it displays in red. My goal is to have the "ball knob" appear yellow when the switch is checked and grey when it is not. This styling must be ...

Create a dynamic animation effect for the placeholder in an input field that triggers when the user starts typing

Have you ever come across interactive demos like this one? I've noticed that most examples involve creating a new element. parent().append("<span>" + $input.attr('placeholder') + "</span>"); Is there a way to make the placehol ...

Is there no sign of rails being utilized in production?

There are some classic image png files located in app/assets/images/... However, in production, after running rake assets:precompile The images do not appear! Upon inspecting the CSS source code, I noticed that .logo { background-image: url("/ass ...

The problem encountered with Electron Forge is: "unable to create a package for Linux with a deb target."

Once again, I am encountering a problem that I just can't seem to resolve... The issue at hand I have developed an Electron application and now I'm trying to build it for Linux. While I managed to successfully create a Windows (Squirrel) bui ...

Button activates SVG animation

Currently, I am working on an animation for a button using SVG. The animation utilizes the classes .is-loading and .is-success. However, when I click on the button, the animation does not execute as expected. I'm having trouble identifying the error w ...

Conceal the browser scrollbars

When I have two DIVs on my webpage that are larger than a browser window, it results in a horizontal scrollbar being displayed. How can I hide this browser scrollbar for the first DIV while still showing it for the second one? For example, if I have two ...

Tips for integrating CSS with Material UI TableContainer

I have utilized Material UI Grid to display data in a chart. However, the appearance of the chart does not match my expectations. Instead of resembling the desired "dense table," it looks different: Actual Look of the Chart Below is the code snippet I ha ...

Creating a looping animation on multiple elements using jQuery that makes them fade in and out at different intervals

I am currently working on creating a fade in and out animation for multiple elements using jquery. It's a bit complex to explain, so I will start by sharing the relevant code. $(document).ready(function() { $("#1").delay(0).animate({ ...

Creating a basic popup with jQuery: A step-by-step guide

Currently in the process of creating a webpage. Wondering how to create a popup window with an email label and text box when clicking on the mail div? ...

Combining HTML, CSS, JAVASCRIPT, and PHP for a seamless web development experience

As a beginner in web development, I have some knowledge of javascript, html, css and am currently delving into php. However, I am struggling to find comprehensive resources that show how to integrate all these languages together. I would greatly appreciat ...

How about connecting Gulp to an Express server?

Is it possible to set up gulp-connect to execute the file at bin/www (express)? I have been unable to get it working, and there doesn't seem to be any documentation on the gulp-connect website regarding configuring or changing the starting file for gu ...

CSS: the enigmatic padding of absolute positioning within a table cell

I am encountering an unusual issue while attempting to position a div element absolutely inside a table-cell. In order to achieve absolute positioning, I utilize a wrapper div element with position:relative: HTML <table> <colgroup> ...

Animating file transfer can be achieved using either JavaScript or CSS

My goal is to create a visual representation of file transfer, such as moving a file from one folder to another. I have successfully achieved this using JavaScript with the following code: <script type="text/javascript> var img; var animateR; var an ...

Aligning list items with Bootstrap

I am struggling with aligning Sheet3 and Science vertically left in a list with checkboxes. Currently, Science goes below the checkbox and I need a solution to fix this alignment issue. https://i.sstatic.net/bxoBT.png Any guidance on how to adjust the al ...