Remove dev and test only code in production builds
The grunt-strip-code plugin is used to remove sections of code from production builds that are only needed in development and test environments. grunt-strip-code uses start and end comments to identify the code sections to strip out. For example:
/* test-code */removeMeInProduction;/* end-test-code */doNotRemoveMe;
This plugin requires Grunt
If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:
npm install grunt-strip-code --save-dev
In your project's Gruntfile, add a section named
strip_code to the data object passed into
gruntinitConfigstrip_code:options:// Task-specific options go here.your_target:// Target-specific file lists and/or options go here.
The text inside the opening comment used to identify code to strip.
The text inside the closing comment used to identify code to strip.
Default value: (a generated RegExp matching the start and end comments)
If the default start and end comment matching doesn't work for you needs, you can supply your own RegExp to match against. If the
pattern option is specified, the
end_comment options are ignored.
The following source code exposes the
bar function to the public API for testing, but the
bar function should not be accessible in the released library. grunt-strip-code (with the default options) will remove the comment blocks from the example below keeping the
bar function private in production:
doSomething;var api =bar;return "foo";/* test-code */api_bar = bar;/* end-test-code */return api;;
The following configuration will strip out code that begins with the
/* start-test-block */ comment and ends with the
/* end-test-block */ comment from all
.js files in the
gruntinitConfigstrip_code:options:start_comment: 'start-test-block'end_comment: 'end-test-block'src: 'dist/*.js'
The following configuration will remove
log() statements from all
.js files in the
gruntinitConfigstrip_code:options:pattern: /log\(\)/gsrc: 'dist/*.js'
The normal behavior is to strip out code in the source files and then save those files with the same name. If you need to save them to a different name, you can specify a
dest option as well.
gruntinitConfigstrip_code:options:files:src: 'tmp/my-app.js' dest: 'dist/my-app.js'src: 'tmp/my-lib.js' dest: 'dist/my-lib.js'
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using Grunt.