Looking at my gulpfile I just realized I must be declaring all of my variables on the global scope.
My gulpfile looks pretty typical (not unlike this one), with a bunch of var
s declared at the top of the file.
var gulp = require('gulp');
var browserify = require('gulp-browserify');
var concat = require('gulp-concat');
var less = require('gulp-less');
var refresh = require('gulp-livereload');
var minifyCSS = require('gulp-minify-css');
But this suggests to me that all of these var
s at the top of the file are just being slapped onto the global object.
Am I being dumb? Should I be wrapping my gulpfile in an IIFE?
And if so, why am I not seeing examples of a gulpfile within an IIFE anywhere online?
Immediately invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function.
An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The name IIFE is promoted by Ben Alman in his blog.
An Immediate-Invoked Function Expression (IIFE) is a function that is executed instantly after it's defined. This pattern has been used to alias global variables, make variables and functions private and to ensure asynchronous code in loops are executed correctly.
Converting Functions to IIFEs Given any regular function definition, wrap the definition within a closed pair of parentheses, this will create your Function Expression. Lastly add another pair of parentheses and a semicolon to mark the end of the statement, and you have converted your regular Function into an IIFE.
gulpfile runs in node, not in browser. In browser these variables would be defined as global. In node this is different. Right from the docs
The top-level scope is not the global scope; var something inside a Node module will be local to that module
So it is OK to define variables without IIFE in gulpfile
Remember that gulp runs in node an in node the behavior of globals is different than the browser.
In browsers, the top-level scope is the global scope. That means that in browsers if you're in the global scope var something will define a global variable. In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.
So those variables are not globals. Node works a little different than the browser so you should read the docs to learn the difference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With