Giter Site home page Giter Site logo

gulp-remove-code's Introduction

gulp-remove-code

JavaScript Style Guide npm version Build Status Build status Dependency Status

A Gulp plugin to remove sections of code from files based on conditions

Install

npm install gulp-remove-code --save-dev

Usage

const removeCode = require('gulp-remove-code');

gulp.src('./src/*.js')
  .pipe(removeCode({ noDevFeatures: true }))
  .pipe(gulp.dest('./dist/'))

gulp.src('./src/*.js')
  .pipe(removeCode({ noDevFeatures: true, commentStart: '/*', commentEnd: '*/' }))
  .pipe(gulp.dest('./dist/'))

gulp.src('./src/*.coffee')
  .pipe(removeCode({ noDevFeatures: true }))
  .pipe(gulp.dest('./dist/'))

Examples

Remove code from HTML files

<div>
  <!--removeIf(production)-->
  <div class="sandbox-banner">Running in sandbox environment</div>
  <!--endRemoveIf(production)-->

  <span>Removing code is easy.</span>
</div>
const removeCode = require('gulp-remove-code');

gulp.src('./src/file.html')
  .pipe(removeCode({ production: true }))
  .pipe(gulp.dest('./dist'))

The plugin will remove the code inside the comments, as well as the comments.

Remove code JavaScript files

let value = JSON.stringify({key: 'value'});

//removeIf(production)
value = JSON.stringify({key: 'value', production: true}, null, 2);
//endRemoveIf(production)

//removeIf(!development)
value = JSON.stringify({key: 'value', development: false}, null, 2);
//endRemoveIf(!development)
const removeCode = require('gulp-remove-code');

gulp.src('./src/file.js')
  .pipe(removeCode({ production: true }))
  .pipe(gulp.dest('./dist'))

The plugin will remove the code inside the comments, as well as the comments.

Advanced usage

Starting with version 2 of this plugin, conditions can also be expressed using the ! specifier.

// Remove code using *!* (negated) conditions

//----------- gulpfile.js -----------
//
const removeCode = require('gulp-remove-code');

gulp.src('./src/file.js')
  .pipe(removeCode({ production: false }))
  .pipe(gulp.dest('./dist'))


//----------- app-file.js -----------
//
//removeIf(!production)
value = JSON.stringify({key: 'value', production: false}, null, 2);
//endRemoveIf(!production)

API

removeCode([options])

options

Type: Object

A key value pair map to specify what code should be removed. The truthy values will remove the code.

options.commentStart

Type: String

Default: Detected from file extension. Use // as fallback.

Configure how the start comment is defined.

options.commentEnd

Type: String

Default: Detected from file extension. Use empty as fallback.

Configure how the end comment is defined.

License

MIT © Cristian Trifan

gulp-remove-code's People

Contributors

chrilith avatar codeman99 avatar crissdev avatar timothydsmith avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

gulp-remove-code's Issues

stream chain broken in case of getBufferContents

In case of getBufferContents callback is only called if parsed instanceof PluginError :

function getBufferContents (file, options, stream, callback) {
  const parsed = removeCode(file, file.contents, options)

  if (parsed instanceof PluginError) {
    stream.emit('error', parsed)
    return callback()
  }

  return parsed
}

But as i read the through2 doc https://www.npmjs.com/package/through2, we need to call it every time.
I'm not sure of what i did but it's work :

function getBufferContents (file, options, stream, callback) {
  const parsed = removeCode(file, file.contents, options)

  if (parsed instanceof PluginError) {
    stream.emit('error', parsed)
    return callback()
  }
  
  callback()
  return parsed
}

Failing 'nsp check'

Hi,

I have a BitBucket Pipeline that runs my build & deploy script. While executing 'npm install' command, the pipeline fails doing "nps check". Not sure what's going wrong there.

I'm using latest gulp-remove-code @ 3.0.0

Here is the log:

[email protected] install /opt/atlassian/pipelines/agent/build/node_modules/uws
node-gyp rebuild > build_log.txt 2>&1 || exit 0
[email protected] postinstall /opt/atlassian/pipelines/agent/build/node_modules/gulp-remove-code
nsp check
sh: 1: nsp: not found
...
...
npm ERR! Linux 4.14.11-coreos
npm ERR! argv "/opt/node/bin/node" "/opt/node/bin/npm" "install"
npm ERR! node v6.14.1
npm ERR! npm v3.10.10
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! [email protected] postinstall: nsp check
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the [email protected] postinstall script 'nsp check'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the gulp-remove-code package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! nsp check
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs gulp-remove-code
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls gulp-remove-code
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! /opt/atlassian/pipelines/agent/build/npm-debug.log

Here is my package.json:
{
"name": "my-app",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "npm run lite",
"lite": "lite-server"
},
"license": "UNLICENSED",
"devDependencies": {
"del": "latest",
"gulp": "latest",
"gulp-clean-css": "latest",
"gulp-concat": "latest",
"gulp-minify": "latest",
"gulp-uglify": "latest",
"gulp-foreach": "latest",
"gulp-rename": "latest",
"gulp-sequence": "latest",
"gulp-remove-code": "latest",
"lite-server": "latest"
}
}

Please help.
Cheers,

Error Handling Anti-Pattern

I see that you are actively refactoring for various reasons. You should consider changing the error handling as well. In a few places you have something like the following.

try {
   if (err) {
      return callback(err);
   }
   // more stuff
} catch (e) {
   callback(e);
}

The usage of the callback inside of your try-catch is bad, especially in streams. That callback quite often synchronously calls the emit method. The emit method will also intentionally re-throw errors if there are no handlers. This is done because crashing is better than silently swallowing errors.

Alex Early explains this well: caolan/async#1458 (comment)

For most of your cases I suggest something like the following.

if (err) {
   return callback(new PluginError(PLUGIN_NAME, err));
}

var e, result;

try {
   result = processSomething();
} catch (err) {
   e = new PluginError(PLUGIN_NAME, err);
}

callback(e, result);

Code is not removed from files with .scss file extension

I'm trying to remove code from my Sass files (.scss), but can't seem to get it working.

I'm trying this in my gulp file:

.pipe(removeCode({ responsive: false, commentStart: '/*', commentEnd: '*/' }))

... And this in my .scss file

/*removeIf(responsive)*/ .helloWorld { color: red; } /*endRemoveIf(responsive)*/

Is there a way to make it work?

Returned stream cannot be paused with large number of files.

Trying to use combined-stream directly after gulp-remove-code, but when I do my gulp task fails silently.

If I put another heavy io task after gulp-remove-code like gulp-debug and before combinedStream.append, everything works as expected.

Failing Example (untested):

var gulp = require('gulp');
var removeCode = require('gulp-remove-code');
var combine = require('combined-stream');

gulp.task('default', function(callback) {
    var s = gulp.src('**/*.js'); // say, 70 or so js files with 500 average lines of code
    var h = gulp.src('**/*.html');
    var c = combine.create();

    s = s.pipe(removeCode({umd: true}));

    c.append(s); // the "s" stream is paused, but removeCode is still processing files
    c.append(h);

    c = c.pipe(gulp.dest('out'));

    c.on('end', callback);
});

Suggestion

Would you be interested in adding an additional use syntax?

The proposal, a tag like <-- keepIf(production) --> or <-- removeUnless(production) -->

The block describes what should stay, rather than go, which makes the example below a very clear view of what you're using in dev vs production.

<!-- keepIf(development) -->
  <script src="vendor/jquery-2.1.4.js"></script>
<!-- endKeepIf(development) -->

<!-- keepIf(production) -->
  <script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
  <script src="/js/main.js"></script>
<!-- endKeepIf(production) -->

Happy to do some work on it if you're interested.

Add support for multiple comment formats

Took me a while to figure out why this wasn't working with my PHP files, but I realized it's because PHP wasn't being recognized as using "HTML-style" comments. I rectified it by using the commentStart and commentEnd parameters, but then I got thinking.

What if I needed to remove blocks of HTML code in one part of a PHP file, and PHP code in another part? I suppose I could wrap the HTML parts in <?php /*removeIf(condition)*/ ?> ... <?php /*endRemoveIf(condition)*/ ?>, but then I'd be stuck with an empty <?php ?>, which isn't ideal.

Additionally, what if I want to search multiple file types for the same condition? For example, remove all PHP, HTML, JS, and CSS for a module. I'd have to duplicate a lot of code in my task, saying "check this format, and then this format, and then this one," which again, isn't ideal.

I'd really like to see an option to set commentStart and commentEnd as arrays, something like the following:

gulp.task("init", function () {
    return gulp.src(src + "/**/*")
        // remove login HTML code if --remove --login is passed
        .pipe(gulpif(argv.remove && argv.login, removeCode({no_login: true, commentStart: ["<!--", "/*", "//"], commentEnd: ["-->", "*/", ""]})))
        // return to the source directory
        .pipe(gulp.dest(src));
});

That way you could parse multiple file types at once.

Add option to remove just comments if the value being checked is false

I'm trying to use this module to set up an "init" task that will take some general source files and remove any modules that I don't need for a given project. So far I think I've got a good idea of how this can work, but I'm running in to a small issue.

When passing false as the value for the condition your checking, it'd be nice if there was an additional option removeCommentsIfFalse (or something like that) that would remove just the comments and leave the code within as-is.

I can probably work around this using additional modules and regular expressions, but I think this would a be great feature to bake-in.

Not working with PHP files?

Does this work with PHP? I run removeCode({ production: true }) and have //removeIf(production) with the proper end tag, but it doesn't do anything.

gulp-remove-code does not work with cshtml files

If the file extension is cshtml, then the gulp-remove-code does not recognise the <!--removeIf(production)--> comment within the HTML section. This works fine if I rename the file to html. Please add support for cshtml file format that may contain both html and c# code (<!-- --> or // as comment)

Add option to treat "false" as the required value to remove code

I think in a lot of cases it would be nice to be able to say "remove if false," rather than "remove if true." This is mostly just for naming purposes.

For example, let's say we're trying to remove a block of code that should only show up on a if the page is responsive. Currently, we'd need to set something like the following to remove the responsive code:

<!--removeIf(notResponsive)--->
...
<!--endRemoveIf(notResponsive)-->

It'd be a bit less awkward to say something like:

<!--removeIf(responsive === false)--->
...
<!--endRemoveIf(responsive === false)-->

Minor quibble, I just think the way some situations need to be worded (like the above) could be confusing.

Need function that remove comment without removing what inside.

It would be nice if you could add a function or parameters that remove the "removeIf/endRemoveIf" comments without removing what inside of them.

I use gulp-remove-code to remove some stuff from the minified version of my JS files that I don't want in production, but in the unminified version I keep those thing there, but the "removeIf/endRemoveIf" stay as well.

Would love to be able to keep them but remove the "removeIf/endRemoveIf" comments from the final build.

maybe something like
.pipe(removeCode({ removeCommentsOnly: true }))

Thx.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.