Bundle Angular2 App into package using systemjs

angular2

Assuming you already have an Angular2 app which uses systemjs for loading modules.

for starting from scratch, you can clone this repo for minimal setup of Angular2 App.

  • update package.json

package.json

1
2
3
4
5

"devDependencies": {
	"grunt": "1.0.1",
	"grunt-systemjs-builder": "0.2.7"
}


  • run npm install (to install these new packages)

  • create build.config.js file in root of your app. (this tells systemjs builder which package to include in bundle file)

build.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
System.config({
    meta:{
        '@angular/*':{
            build: false
        },
        'rxjs/*': {
            build: false
        }
    },
    paths:{
        "dist/*": "./dist/*.js"
    }
});


  • create Gruntfile.js in root of your app.

Gruntfile.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
module.exports = function (grunt) {
	grunt.initConfig({
		systemjs: {
			dist: {
				options: {
					sfx: true,
					baseURL: "./",
					configFile: "./build.config.js",
					minify: true,
					sourceMaps: false
				},
				files: [{
					"src": "./dist/main.js",
					"dest": "./build/main.js"
				}]
			},
			dev: {
				options: {
					sfx: true,
					baseURL: "./",
					configFile: "./build.config.js",
					minify: false,
					sourceMaps: true,
					build: {
						mangle: false
					}
				},
				files: [{
					"src": "./dist/main.js",
					"dest": "./build/dev.js"
				}]
			}
		}

	});

	grunt.loadNpmTasks('grunt-systemjs-builder');

	grunt.registerTask('build', ['systemjs']);
};


  • update system.config.js file (system js configuration file)

system.config.js

1
2
3
4
5
6
7
// our app is within the app folder

// from bundle
app: 'build',

// from source
// app: 'dist',


make sure grunt cli is also installed globally

  • to bundle run grunt build from powershell / terminal

  • now compile and run your app, instead of multiple files (based on size of project) single bundled file will be loaded

this structure can be further used for dependency injection.