Using Gulp Filter in Conjunction with Source Maps

My initial query was similar to this one here, but it led me to delve deeper into research and explore a new approach.

Essentially, I am attempting to consolidate all my .js and .coffee files within a single gulp.src() object and execute relevant tasks based on the file extension.

What started as an exploration with gulp-if has evolved into utilizing gulp-filter, which I find preferable. However, I am currently facing challenges in harmonizing this setup with gulp-sourcemaps. It appears that the current task is overriding others; nevertheless, my ultimate goal is to concatenate everything into one file, source-map it into another, and have each file extension trigger its respective tasks. The commented-out uglify task continues to cause issues without providing much guidance. Additionally, when the filters are functioning and a CoffeeScript error occurs, I observe that coffeescriptlint() executes its duty, but then my watch command remains unresponsive.

It seems like I might be heading towards extracting each sourcemap using a tool like gulp-extract-sourcemap, although I am unsure if that is the correct approach.

Usually, I would separate the JS and Coffeescript tasks; however, due to numerous intertwined aspects between the two, combining them using a simple filter seemed rational—especially since I am grappling with sourcemaps for both.

I believe I am close to resolving this issue, so any helpful nudges in the right direction would be highly appreciated. I have included the current gulpfile.js and package.json if you wish to test it out. Thank you!

Gulpfile.js

// Load plugins
var gulp       = require('gulp'),
    jshint     = require('gulp-jshint'),
    coffee     = require('gulp-coffee'),
    changed    = require('gulp-changed'),
    coffeelint = require('gulp-coffeelint'),
    uglify     = require('gulp-uglify'),
    sourcemaps = require('gulp-sourcemaps'),
    notify     = require('gulp-notify'),
    concat     = require('gulp-concat'),
    filesize   = require('gulp-size'),
    livereload = require('gulp-livereload'),
    duration   = require('gulp-duration'),
    gutil      = require('gulp-util'),
    gFilter     = require('gulp-filter');

gulp.task('scripts', function() {
  var jsBuildDir = 'assets/js/build/',
      jsFilter = gFilter('**/*.js'),
      coffeeFilter = gFilter('**/*.coffee');

    return gulp.src([
      'assets/js/src/_init.coffee',
      'assets/js/src/_init.js'
    ])
    .pipe(coffeeFilter)
      .pipe(coffeelint().on('error', gutil.log))
      .pipe(coffeelint.reporter())
      .pipe(sourcemaps.init())
        .pipe(coffee({bare: true}).on('error', gutil.log))
      .pipe(sourcemaps.write('../../maps'))
    .pipe(coffeeFilter.restore())
    .pipe(jsFilter)
      .pipe(jshint({
            'boss': true,
            'sub': true,
            'evil': true,
            'browser': true,
            'globals': {
              'module': false,
              'require': true
            }
         }),
         jshint.reporter('jshint-stylish'))
    .pipe(jsFilter.restore())
    .pipe(concat('scripts.min.js'))
    //.pipe(uglify())
    .pipe(filesize({
      title: 'Scripts:'
    }))
    .pipe(gulp.dest(jsBuildDir))
    .pipe(duration('building script files'))
    .pipe(notify({ message: 'Coffeescript task complete' }));
});

// Default task
gulp.task('default', ['scripts']);

// Watch
gulp.task('watch', function() {

  gulp.watch(['assets/js/src/**/*.js', 'assets/js/src/**/*.coffee'], ['scripts']);

  // Create LiveReload server
  var server = livereload();

  // Watch files in patterns below, reload on change
  gulp.watch(['assets/js/build/*']).on('change', function(file) {
    server.changed(file.path);
  });

});

Package.json

{
  "devDependencies": {
    "gulp": "^3.8.8",
    "gulp-changed": "^1.0.0",
    "gulp-coffee": "^2.2.0",
    "gulp-coffeelint": "^0.4.0",
    "gulp-concat": "^2.4.0",
    "gulp-duration": "0.0.0",
    "gulp-filter": "^1.0.2",
    "gulp-jshint": "^1.8.4",
    "gulp-livereload": "^2.1.1",
    "gulp-notify": "^1.6.0",
    "gulp-size": "^1.1.0",
    "gulp-sourcemaps": "^1.2.2",
    "gulp-uglify": "^1.0.1",
    "gulp-util": "^3.0.1",
    "jshint-stylish": "^0.4.0"
  }
}

Answer â„–1

It seems like the placement of sourcemaps.init() and sourcemaps.write() in your pipe may be incorrect. I have rearranged them below to where I believe they should be for optimal functionality.

I made use of gulp-filter sparingly to avoid overcomplicating things, and found run-sequence to be very useful in this scenario. You can also refer to some of my gulpfiles here and here.

In your case, I would approach the situation as follows:

var runSequence = require('run-sequence');
// ...

gulp.task('scripts', function (done) {
  runSequence('lint', 'build', done);
});

gulp.task('lint', function (done) {
  runSequence('lint-coffee', 'lint-js', done);
});

gulp.task('lint-coffee', function () {
  // Lint coffee files here...
});

gulp.task('lint-js', function () {
  // Lint js files here...
});

gulp.task('build', function () {

  return gulp.src([
    'assets/js/src/_init.coffee',
    'assets/js/src/_init.js'
  ])
  .pipe(coffeeFilter)
    .pipe(coffee({bare: true}).on('error', gutil.log))
  .pipe(coffeeFilter.restore())
  .pipe(sourcemaps.init())
    .pipe(concat('scripts.min.js'))
    .pipe(uglify())
  .pipe(sourcemaps.write('../../maps'))
  .pipe(gulp.dest(jsBuildDir));

});

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

When attempting to print certain attributes, the Node.JS array unexpectedly becomes undefined

While attempting to print a specific attribute such as "Full time or part time" in the getEmployeesByStatus() function, I encountered an issue where it suddenly returns undefined even though the entire array prints when I try to display it. This problem ha ...

What is the best way to integrate my custom JavaScript code into my WordPress theme, specifically Understrap?

I am looking to enhance my website with a sticky navbar positioned directly under the header, and I want it to stick to the top of the page as users scroll down. Additionally, I want the header to disappear smoothly as the user scrolls towards the navbar. ...

Angular 2 Element Selection: Dealing with Unrendered Elements

This form consists of three input fields: <div> <input *ngIf = "showInputs" #input1 (change)="onTfChnage(input2)" type="text"/> <input *ngIf = "showInputs" #input2 (change)="onTfChnage(input3)" type="text"/> <input *ngIf = "showInp ...

Determining when all $http requests have completed in AngularJS

After running multiple $http calls, I need to trigger an event only when all of them have been processed. Additionally, I must be informed if any call has failed along the way. Despite attempting solutions found on stackoverflow, such as using an intercept ...

Utilizing the $.ajax method along with the onreadystatechange event

Is there a way to use the onreadystatechange event of the underlying XMLHttpRequest in JQuery's (version 2.0.2) $.ajax(...) function to trigger synchronous ajax requests for displaying accurate status indications during long-running processes? It seem ...

- Challenges with internal systems

I have a dialog window where I want to display a confirm dialog when clicking Cancel. To achieve this, I am creating a div element with some text that should be shown in the confirm dialog. However, the issue I'm facing is that the text intended for t ...

Issue detected: The validation form is encountering errors due to a blank textarea when utilizing jQuery validate and AJAX for

I am currently working on a spring project that involves registering comments on a specific system design. The page layout for this task is as follows: <form id="formularioCadastroComentario" role="form" method="POST" class="form-horizontal"> &l ...

What is the best way to traverse through a nested JSON file with d3.js?

Greetings. I am currently facing a challenge in navigating through a nested JSON file. Below is the JSON data that I need assistance with: {"Id":466,"Name":"korea", "Occurrences": ...

Tips for getting a sticky table header and including a limited number of columns, each with checkboxes or input fields

Encountering issues while trying to implement functionality with a jQuery library. One specific problem is the inability to interact with checkboxes on sticky columns, as well as difficulties clicking and typing in text fields. I am utilizing the jQuery S ...

Is there a way to automatically submit an upload form once a file has been selected?

Need help with automatically submitting a file upload form when a file is selected. Is there a way to bypass the need for the user to click the Submit button? ...

The values returned by the Node.js API can vary for identical requests

I am currently learning how to use Node.js + Express in order to create a REST API. Within this API, I have implemented the following method: apiRouter.route('/training/session/byId/:id_session') // ===== GET ======= .get(function(req, res ...

Using regex, match any word along with the preserved white space and consider parentheses as a single word

I need help with creating a regex pattern to split a string of words in a specific way. The current pattern I've been using is (?!\(.*)\s(?![^(]*?\)), but it's not giving me the desired outcome. It's close, but not quite the ...

Guide to adjusting column width in an XLSX worksheet using Angular4

I am trying to convert HTML into an XLSX sheet in Angular using SheetJS. However, I am encountering an issue where the width of each column is limited to 256 only, and I need to increase it. I have attempted to use ws[!cols] of ColInfo, but I am strugglin ...

Changing the width of the file input using css

Clicking just below the word demonstration also triggers a click on the input type file. How can this be avoided so that the click event only fires in the intended area regardless of size? <!DOCTYPE html> <html> <body> <style> in ...

Clicking two times changes the background

I am facing an issue with three boxes on my website. Each box is associated with a corresponding div. When I click on any box, the div displays and the background color turns red. However, when I click on the same box again, the div disappears but the back ...

What is the best way to integrate NPM modules with Django in an application?

I am working on a Django project that consists of 2 apps. I need to incorporate the Notion API into one of the apps, which requires me to install its NPM module. The challenge is that I have no experience with NPM or bundlers (which I understand are needed ...

Ways to decrease font size and insert a line break within a constrained input space?

I am facing an issue where the input box remains static with old numbers when it overflows, and newly typed numbers do not appear at all. <!DOCTYPE html> <html> <body> <input type="text" id="output-area" placehold ...

What is the best way to prioritize items on a list in JavaScript?

Looking to organize your to-do list items by priority? In this task list, users can enter an item, select a priority level, and add it to the list. Here is an example HTML form: <input id="task" type="text"/> <select id="priority"> <o ...

Running `npm install npm` results in encountering gyp ERR and npm ERR

Why am I encountering this peculiar error message when executing sudo npm install npm? This issue seems to crop up occasionally with other modules as well! Error: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4a7b7a6ad ...

Utilizing JQuery to extract element tags exclusively, without including their interior content

I am trying to work with a string that includes HTML and I need to remove the span element entirely while preserving its contents within the string (specifically, I want to retain the word "Canadian" and any other elements). var htmlString = <p>Th ...