Skip to content

Instantly share code, notes, and snippets.

@Xiphe
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xiphe/9e34848f19e958946040 to your computer and use it in GitHub Desktop.
Save Xiphe/9e34848f19e958946040 to your computer and use it in GitHub Desktop.

How to use require in angular 1.x modules

  • embrace module structure (1x require = module is available)
// my/app.js
require('../dep/app');
angular.module('myApp', ['dep']);
require('./value');
require('./directive');
// my/value.js
angular.module('myApp').value('myValue', 'foo');
// my/directive.js
angular.module('myApp').directive('myDirective', function(depService, myValue) {
	/* ... */
});
// dep/app.js
angular.module('dep', []);
require('./service');
// dep/service.js
angular.module('dep').service('depService', /* ... */);

Add the module to the dependencies of wrapper/cms/siteadmin frame app

// wrapperFrameApp.js
require('./my/app');
angular.module('wrapperFrameApp', [..., 'myApp']);

External Component, will be used in blob

don't provide minified file as main entry with bundled dependencies, but depend on bundling of the blob (or other context) package.json stuff may change

// MyComponent/src/app.js

var $ = require('jquery'); // dependency that might be provided by context, may be resolved to window.jquery

$(function() {
	require('./File.js').doStuff(); // stuff in my module
	require('colorpicker').pick(); // external dependency of MyComponent
});
// MyComponent/dist/app.js

window.jQuery(function() {
	var a = {...};
	a.doStuff();

	window.b.pick();
});
// MyComponent/bower.json
{
	"dependencies": {
		"jquery": "*",
		"colorpicker": "*"
	},
	main: "dist/app.js"
}
// MyComponent/package.json
{
	"dependencies": {
		"jquery": "*",
		"colorpicker": "*"
	},
	main: "src/app.js"
}

jQuery Registry Style

// Stuff.js
require('web/scripts/registry.js');
require('../Module.js');
require('../CC.js');

var jQuery = require('jquery');
/* ... */

jQuery.reg('ModuleStuff extends Module', function( _super, $, cc ) {
    "use strict";

    var self = this;

    this.init = function() {
        _super.init(self);

        ...
    };

    this.doStuff = function () {

    };
});
// Usage.js
require('web/scripts/registry.js');
require('../Module/Stuff.js');

$.reg.get('moduleStuff').doStuff();

Lazy Load

// Stuff.js

var Stuff = {
	doStuff: function () {...}
}
// Usage.js

$(document).ready(function () {
	require.ensure([], function (require) {
		var Stuff = require('Stuff.js'); // may be lazy loaded, is synchronous available after this line

		Stuff.doStuff();
	});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment