Skip to content

Instantly share code, notes, and snippets.

@princejwesley
Created November 23, 2015 13:07
Show Gist options
  • Save princejwesley/85442079383e2dd9d10f to your computer and use it in GitHub Desktop.
Save princejwesley/85442079383e2dd9d10f to your computer and use it in GitHub Desktop.
Gulp pipe-able function for creating angular modules only when its not already created
var through = require('through2');
var moduleWrapper = through.obj(function (chunk, enc, cb) {
var content = chunk._contents.toString();
var newContent = content.replace(/angular\s*\.\s*module\s*\(\s*['"]([^'"]+)['"]\s*,\s*\[([^\]]*)\][^)]*\)/mg, function(match, mod, deps) {
// ignore ngHtml2Js templates module name
// if(mod === 'app.templates') { return match; }
return "((function () {\n try {\n return angular.module('" + mod + "');\n } catch (e) {\n return angular.module('" + mod + "', [" + deps + "]);\n }\n})())";
});
chunk._contents = new Buffer(newContent);
cb(null, chunk);
});
@princejwesley
Copy link
Author

Transform angular.module('module-name', [ 'dep1', 'dep2' ]) to

((function () {
  try {
    return angular.module('module-name');
  } catch (e) {
    return angular.module('module-name', ['dep1', 'dep2']);
  }
})())

Usage:

gulp.src(..)
  .pipe(..)
  .pipe(moduleWrapper)
  .dest(...);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment