Wraps JavaScript code within and IIFE.
npm install grunt-iife>=0.4.0
sh
$ npm install --save-dev grunt-iife
`
Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:
`js
grunt.loadNpmTasks('grunt-iife');
`
:zap: Usage
This configuration will wrap JS files using the default options.
`js
// Project configuration.
grunt.initConfig({
iife: {
myTarget: {
files: {
'dest/output.js': 'src/input.js'
}
}
}
});
`
So, if input file looks like this:
`js
var foo = 'bar';
console.log(foo);
`
Then output file will be like this:
`js
;(function() {
'use strict';
var foo = 'bar';
console.log(foo);
}());
`
:wrench: Options
You can pass additional options to change output file:
- useStrict
- prependSemicolon
- bindThis
- trimCode
- args
- params
- indent
$3
Type: Boolean
Default: true
A boolean indicating whether to prepend a 'use strict'; directive to the function body.
$3
Type: Boolean
Default: true
A boolean indicating whether to prepend a semicolon as statement terminator before the IIFE.
$3
Type: Boolean
Default: false
A boolean indicating whether to append .bind(this) to the IIFE. Setting this value to true makes the surrounding global object available to the function, which is usually not the case in strict mode.
$3
Type: Boolean
Default: true
A boolean indicating whether to remove leading & trailing whitespace from the code.
$3
Type: String[]
Default: null
An array of argument names to be passed into the IIFE. If the params option is not specified, the parameters of the function will have the same names as the arguments passed.
$3
Type: String[]
Default: null
An array of parameter names to be accepted by the IIFE. If the args option is not specified, the same identifiers will be passed as arguments of the function call.
$3
Type: String
Default: null
A string value that is used to indent.
Here's an example specifying all available options:
`js
grunt.initConfig({
iife: {
myTarget: {
options: {
useStrict: true,
prependSemicolon: false,
bindThis: true,
trimCode: true,
indent
args: ['window', '$'],
params: ['window', 'jQuery']
},
files: {
'dest/output.js': 'src/input.js'
}
}
}
});
`
Input file:
`js
var foo = 'bar';
console.log(foo);
`
Output file:
`js
(function(window, $) {
'use strict';
var foo = 'bar';
console.log(foo);
}(window, jQuery));
``