1

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"));
});
  • Are you talking about some kind of bundler system such as [Wepback](https://github.com/webpack/webpack) ? – Pierre Criulanscy Jul 15 '16 at 13:11
  • No, just doing this "manually" by using Gulp. – mostlybitwise Jul 15 '16 at 13:25
  • 1
    This is what they usually do in the past ten years. The 2016 way is to use standard modules and a bundler like rollupjs. See http://stackoverflow.com/questions/31593694/do-i-need-require-js-when-i-use-babel – Tamas Hegedus Jul 15 '16 at 13:35
  • @TamasHegedus, thank you so much! rollup.js with it's options set to produce the output as a self-executing function is exactly what I needed! – mostlybitwise Jul 15 '16 at 14:12

0 Answers0