Search code examples
angularjsbrowserifycommonjs

How to write commonjs pattern module of AngularJS


All:

I am pretty new to browserify and commonjs pattern. When I try how broserify work with Angular, I use a very simple Example:

//main.js

require("angular");
var app = angular.module("app", []);

And:

// controller.js
require("angular");
angular.module("app");
        .controller("main", function($scope){
            $scope.message = "Hello";
        });

And for Gulp I use:

// gulpfile.js

var gulp = require("gulp");
var browserify = require('browserify');
var source = require('vinyl-source-stream');


gulp.task('browserify', function() {
    // Grabs the app.js file
    return browserify('./app/main.js')
        // bundles it and creates a file called main.js
        .bundle()
        .pipe(source('bundle.js'))
        // saves it the dest/ directory
        .pipe(gulp.dest('./dest/'));
})

But this does not work(I know this for sure, but just no idea how to make it do), I tried add require("./controller"); but with no luck.

I wonder how can I add that controller.js as commonjs required module and browserify them, or anyway(if we do not need to add it) just make it work in commonjs pattern.

One post I find talking about this: http://ardeibert.com/modularizing-an-angularjs-app-with-browserify/ But its way is only export all controller functions, I still need to register them in main.js, if so, I am wondering how do I use other service/factory in controller.js like dependency injection?

I thought the reason to use browserify is it can help to figure out the dependency structure, but I wonder how can I make it known the relation between app module and the main controller?

Thanks


Solution

  • Your controller file should export the value that you want to be available whenever you require it. In this case you could export the controller function.

    // controller.js
    module.exports = function($scope){
      $scope.message = "Hello";
    }
    

    Then require it in your main application file.

    //main.js
    
    var angular = require("angular");
    var MainController = require("./controller");
    
    var app = angular.module("app", []);
    
    app.controller("main", MainController);
    

    Personally, as my projects get bigger, I like to make each file a module so that they can include multiple providers and directives. Then the export/require pattern becomes slightly different.

    // my-module.js
    var angular = require('angular');
    
    angular.module('MyModule', [])
      .service('MyService', function() { ... })
      .directive('MyDirective', function() { ... });
    

    Then you need to require the module and inject into your app's main module.

    // main.js
    var angular = require('angular');
    require('./my-module');
    
    angular.module('MyApp', ['MyModule'])
      .controller('MyController', function(MyService) {
        // injected service from MyModule
      });