mostlybitwise
mostlybitwise

Reputation: 11

Concatenating JavaScript files and enclosing them into a self invoking function - possible downsides?

It is possible to concatenate several JavaScript files into one and then enclose the resulting code into a self invoking function, so all the code from these JS files turns into:

;(function () { /* code form the JS files */ })();

In this way there is no pollution of the global namespace at all and now there can be internal modules defined in separate JS files that can be accessed across JS files.

Aside from making debugging of the internal modules less convinient (as it won't be possible to browse internal objects, call their functions manually from the console, etc.) are there any potential downsides this approach can have?

Or, is there a better way to allow internal modules to be defined in separate JS files that can be accessed across JS files?


Just in case, the gulp code that concatenates JavaScript files into one and then encloses the resulting code into a self invoking function:

var gulp = require("gulp");
var sourcemaps = require("gulp-sourcemaps");
var uglify = require('gulp-uglify');
var concat = require("gulp-concat");
var insert = require("gulp-insert");

gulp.task("default", function () {
    return gulp.src("js/app/*.js")
        .pipe(sourcemaps.init())
        .pipe(concat("app.js"))
        .pipe(insert.transform(function(contents, file) {
            return ';(function () {' + contents + '})();';
        }))
        .pipe(uglify())
        .pipe(sourcemaps.write("."))
        .pipe(gulp.dest("build/assets/js"));
});

Upvotes: 1

Views: 303

Answers (0)

Related Questions