Search code examples
javascriptarraysgruntjsgrunt-contrib-concat

Ignore array of files with Grunt


If I have an array of files in my Gruntfile like so:

var jsFiles = [
  'src/js/abc.js',
  'src/js/def.js'
]

How can I exclude each file in this array without having to prepend ! to each file? This pattern doesn't seem to work for me:

!jsFiles

I would also love to be able to do !<%= project.jsFiles %> where <%= project.jsFiles %> is an array of files.

There are a number of similar questions on Stack Overflow but not one that addresses ignoring an array of files, from what I can see.


Solution

  • Negate array of files:

    If your want to negate a list of files, like this:

    var jsFiles = [
      'src/js/abc.js',
      'src/js/def.js'
    ];
    

    You can create a function to add the "!":

    function addErase(jsFiles){
      var arr = [];
      jsFiles.forEach(function(element){
        arr.push("!" + element);
      });
      return arr;
    }
    

    Then you can transform your array:

    var jsFileErase = addErase(jsFiles);
    //   ['!src/js/abc.js',
    //   '!src/js/abc.js']
    

    If you want to put the list in the package.json:

    Package.json:

    {
      "name": "foo",
      "version": "0.0.1",
      "jsFiles":[
        'src/js/abc.js',
        'src/js/def.js'
      ],
      ...
    

    Inside Gruntfile.js:

    var project = require('./package.json');
    var jsFiles = project.jsFiles;
    

    Then you can negate all the files with the function addErase

    Negate all element inside a folder:

    If you want to negate all the elements inside a folder, you need to put "!" before the path and "/**/*" at the end of the path:

    Example:

    var jsFile = '!src/js/**/*'