Skip to content

Instantly share code, notes, and snippets.

@apparentlymart
Last active August 29, 2015 14:26
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 apparentlymart/6679a9d9d4f4cbdefa1f to your computer and use it in GitHub Desktop.
Save apparentlymart/6679a9d9d4f4cbdefa1f to your computer and use it in GitHub Desktop.
AngularJS-Server with Browserify example

angularjs-server with browserify example

This is a basic example of using AngularJS-server with browserify. Since browserify requires bundling, unlike the plain example in the AngularJS-Server readme we need to provide a bundle to both the server-side Angular context and to the browser.

The two bundles can be created using browserify:

  • browserify commonapp.js -o serverbundle.js
  • browserify clientapp.js -o clientbundle.js

Then you can run the app, which creates a server on port 3000:

  • node server.js
// This wraps the commonapp module and adds two extra steps that are
// only run on the client, and not run inside the AngularJS-server context.
require('./commonapp.js');
// On the client we need the "real" ngRoute, since our server-side overridden
// implementation is not available.
var angularRoute = require('angular-route');
// Actually bootstrap the app.
// (On the server this is done automatically by the AngularJS-server middleware)
angular.bootstrap(document, ['browserifytest', angularRoute]);
// This is code that runs on both the client and
// inside the angularjs-server context.
var angular = require('angular');
// Declaring 'ngRoute' as a dependency is a no-op inside angularjs-server,
// where it has its own built-in implementation of ngRoute, but in the
// clientapp.js we'll load the "real" angular-route for the client's benefit.
var app = angular.module('browserifytest', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/', {
template: '<p>Hello {{name}}</p>',
controller: function ($scope) {
$scope.name = 'world';
}
});
});
<html>
<head>
<title>Hello World</title>
</head>
<body ng-view></body>
</html>
{
"name": "example",
"version": "0.0.0",
"devDependencies": {
"browserify": "",
"angularjs-server": "",
"angular": "",
"angular-route": ""
},
"dependencies": {
"express": ""
}
}
var angularserver = require('angularjs-server');
var express = require('express');
var fs = require('fs');
var template = fs.readFileSync('index.html', 'utf-8');
var app = express();
var angularMiddlewares = angularserver.Server({
template: template,
serverScripts: [
'serverbundle.js'
],
clientScripts: [
'clientbundle.js'
],
angularModules: [
'browserifytest'
]
});
// Make the scripts and other assets available to the browser.
app.use('/static', express.static('.'));
app.use(angularMiddlewares.htmlGenerator);
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment