397

What is the best method to bundle Angular (version 2, 4, 6, ...) for production on a live web server.

Please include the Angular version within answers so we can track better when it moves to later releases.

Community
  • 1
  • 1
Pat M
  • 5,966
  • 7
  • 24
  • 34
  • For now (rc1). Here are a few solutions [stackoverflow.com/questions/37324511/how-to-bundle-angular2-rc1-with-systemjs](http://stackoverflow.com/questions/37324511/how-to-bundle-angular2-rc1-with-systemjs) – Pat M Jun 06 '16 at 17:35
  • And this one http://stackoverflow.com/questions/37098942/how-to-prevent-angular2-core-making-dozens-of-http-requests-on-page-load/37098964#37098964 – Pat M Jun 07 '16 at 21:33
  • rc3 now offers a bundled file versions that lowers the number of requests from 300+ to about 40. – Pat M Jun 29 '16 at 19:16
  • 2
    Hey. I also hate WebPack's and build steps in general. Sort of overkill for just trying to throw together a simple website. Thus I made this: https://github.com/schungx/angular2-bundle – Stephen Chung Oct 11 '16 at 05:55
  • Thank you Stephen. This would be a simple solution for the vendors part. Hoping this could be officially offered and updated. I suppose you use something like Gulp for the project`s files? – Pat M Oct 11 '16 at 14:00
  • Well, lower tech than Gulp... *sweat drop* My projects are mostly all TypeScript and I set the TypeScript compiler to merge all my modules into a single script file. Sort of a "poor man's Gulp". There is a setting for that. – Stephen Chung Oct 12 '16 at 01:21
  • @StephenChung Would this bundle work on Plunker? – Aakash Thakur Feb 14 '17 at 08:41
  • @AakashThakur No idea! (*sweat drop*) – Stephen Chung Mar 11 '17 at 09:13

14 Answers14

401

2 to 15 (TypeScript) with Angular CLI

OneTime Setup

  • npm install -g @angular/cli
  • ng new projectFolder creates a new application

Bundling Step

  • ng build (run in command line when directory is projectFolder).

    flag prod bundle for production is now the default (see the Angular documentation to customize it if needed).

  • Compress using Brotli compression the resources using the following command

    for i in dist/*/*; do brotli $i; done

bundles are generated by default to projectFolder/dist(/$projectFolder for v6+)**

Output

Sizes with Angular 14.0.2 with CLI 14.0.2and option CSS without Angular routing

  • dist/main.[hash].js Your application bundled [ size: 117 KB for new Angular CLI application empty, 35 KB compressed].
  • dist/polyfill-[es-version].[hash].bundle.js the polyfill dependencies (@angular, RxJS...) bundled [ size: 33 KB for new Angular CLI application empty, 11 KB compressed].
  • dist/index.html entry point of your application.
  • dist/runtime.[hash].bundle.js webpack loader
  • dist/style.[hash].bundle.css the style definitions
  • dist/assets resources copied from the Angular CLI assets configuration

Deployment

You can get a preview of your application using the ng serve --prod command that starts a local HTTP server such that the application with production files is accessible using http://localhost:4200. This is not safe to use for production usage.

For a production usage, you have to deploy all the files from the dist folder in the HTTP server of your choice.

Nicolas Henneaux
  • 11,507
  • 11
  • 57
  • 82
  • I got the error when running npm install -g angular-cli@webpack: npm ERR! Please include the following file with any support request: ....\npm-debug.log. Do you know what's going on? – Chong Wang Aug 29 '16 at 21:09
  • @Chong If you are running on Windows, you should disable the anti virus during the installation otherwise I can't tell you without détails on the error. – Nicolas Henneaux Aug 30 '16 at 03:52
  • installing angular-cli@webpack didn't work for me, but `npm install angular-cli@1.0.0-beta.15` does the trick. However, I had to apply [this patch](https://github.com/angular/angular-cli/pull/2178/commits/65393147df665f45ebe835a10a3de4c68728d324) to fix the "TypeError: path must be a string or Buffer" problem described in [issue 2135](https://github.com/angular/angular-cli/issues/2135) – chrisv Sep 20 '16 at 06:04
  • Thanks @chrisv that was an error, I have made a change. – Nicolas Henneaux Sep 20 '16 at 06:11
  • when running `ng init` i get `Cannot find module 'portfinder'` – Peter Sep 20 '16 at 16:12
  • @Peter you should create a new question with more details since I cannot figure out what is going on only with the error. – Nicolas Henneaux Sep 21 '16 at 03:58
  • Finally angular-cli works fine, I', really happy about it. – Andzej Maciusovic Sep 23 '16 at 07:07
  • Does it minify and inline css/html into the components like A_Singh's answer? – chrismarx Sep 27 '16 at 13:38
  • 2
    @chrismarx it produces only one bundle including all the components with their html and styles. – Nicolas Henneaux Sep 27 '16 at 17:49
  • 4
    I had an application and i wanted to use this method, so i launch ng init from the project folder. I have done the rest of the steps but when i deploy my applications it seems to be empty. The only thing that appears is a "app works!" message, is ther some place where i have to set where to take my app files? – mautrok Oct 25 '16 at 10:52
  • @mautrok If your app already exist you have to merge your file with the file generated by angular-cli such that your application is bundled. Have a look to what is generated and replace the content of app.module.ts by your application module. – Nicolas Henneaux Oct 25 '16 at 12:10
  • My main.xyz.bundle.map file is over 15megs when I run ng build --prod. I assume I can omit these on production? (it just means I won't be able to debug as easily on Prod I guess) – Rodney Nov 23 '16 at 00:21
  • @Rodney Yes exactly, you don't have to bundle the map files. The only drawback is that debugging your prod application will be harder. – Nicolas Henneaux Nov 23 '16 at 04:52
  • @Illorian aot works with cli beta 24 ; beta23 of CLI was broken (see https://github.com/angular/angular-cli/blob/master/CHANGELOG.md) – Nicolas Henneaux Dec 21 '16 at 06:28
  • @NicolasHenneaux i'm still have an error: ERROR in MainModule is not an NgModule – Illorian Dec 22 '16 at 06:40
  • @Illorian you should submit a bug report to the angular cli GitHub with the full detail of your problem – Nicolas Henneaux Dec 22 '16 at 07:06
  • @NicolasHenneaux Once you have this bundle, how do you deploy it a server? (for example, tomcat) – Gab Jan 06 '17 at 16:12
  • @GabrieleB-David you have to include these files into the war you deploy on Tomcat. – Nicolas Henneaux Jan 07 '17 at 12:23
  • I can able to to the build and dist folder also created. But if I open Index.html my project should open right? It showing just "Loading" and whatever the files is created is smaller in size, I don't think dist folder created based on my project. I have given correct path everything. I am using latest angular2. What is the reason? – raj m Jan 27 '17 at 04:28
  • @rajm You need to use a HTTP server since opening the index.html from file system is not supported. You can either use the command `ng server --prod --aot` that start an HTTP server with production files with Angular CLI or use an external HTTP server with the file from the `dist` folder. – Nicolas Henneaux Jan 27 '17 at 17:46
  • Actually there is no app folder is created inside dist folder. So its showing error. What is the reason – raj m Feb 01 '17 at 05:26
  • @rajm Indeed there is no app folder, you should ask a question with the details of your error it will be easier to help you – Nicolas Henneaux Feb 01 '17 at 05:51
  • just posted here.. http://stackoverflow.com/questions/41972749/angular2-cli-not-creating-app-folder-files-and-some-other-files-in-dist-folder.. please help me – raj m Feb 01 '17 at 05:52
  • @NicolasHenneaux i am using visual studio so how can i do it ? – LittleDragon Feb 14 '17 at 09:39
  • @LittleDragon It it not related to an IDE since it is only command line instructions. However, I know that Intellij has a plugin to bind its lifecycle with Angular CLI. It seems it is not possible for the moment with Visual Studio but you can have a look a these GitHub issues talking about that [2453](https://github.com/angular/angular-cli/issues/2453), [2058](https://github.com/angular/angular-cli/issues/2058) and [2960](https://github.com/angular/angular-cli/issues/2960). – Nicolas Henneaux Feb 14 '17 at 09:47
  • How to compress dist folder generated from ng build --prod --aot using Brotli compression – Prithvi Uppalapati Mar 27 '17 at 07:28
  • You should use the command I have included in the answer (`for i in dist/*; do bro --input $i --output $i.br; done`) – Nicolas Henneaux Mar 27 '17 at 07:41
  • How do I install the `bro` command for Brotli compression in Windows? – Svein Fidjestøl Mar 29 '17 at 07:09
  • @SveinFidjestøl you could try this [binary](https://bayden.com/dl/brotli.exe) described in this [blog post](https://textslashplain.com/2015/09/10/brotli/). – Nicolas Henneaux Mar 29 '17 at 07:38
  • What do you do with the br files that are generated? They just all got spit out into the dist folder, now what? – liquid_diamond Apr 13 '17 at 02:00
  • @canada11 if your http server support it, you can return them when the JavaScript file is requested and the accept encoding br is supported by the client, i.e. the header "Accept-Encoding: br" is present in the HTTP header of the request. – Nicolas Henneaux Apr 13 '17 at 03:45
  • 2
    ng-init has been removed from angular cli. https://github.com/angular/angular-cli/issues/5176 – Pat M May 12 '17 at 18:08
  • 2
    I finally marked this as the accepted answer. Although other solutions may work as well and even provide some extra flexibility (I posted one about using Webpack without CLI). Using Angular CLI is definitively the one that gives the less headaches. I ended up using Angular CLI and adapting my project so I can use AoT more easily. – Pat M May 16 '17 at 20:55
  • Does anyone have any idea, how to host an angular app (with server-side rendering) enabled? – Saumya Rastogi Sep 07 '17 at 11:15
  • @NicolasHenneaux As google has now merged Angular Universal with Angular 4, then I think there is no need to see Angular Universal anymore... – Saumya Rastogi Sep 07 '17 at 12:12
  • where should I run `for i in dist/*; do brotli $i; done` – RICKY KUMAR Aug 11 '19 at 17:43
  • In the root folder of your project, where the `dist` folder is located – Nicolas Henneaux Aug 11 '19 at 20:06
61

2.0.1 Final using Gulp (TypeScript - Target: ES5)


OneTime Setup

  • npm install (run in cmd when direcory is projectFolder)

Bundling Steps

  • npm run bundle (run in cmd when direcory is projectFolder)

    bundles are generated to projectFolder / bundles /

Output

  • bundles/dependencies.bundle.js [ size: ~ 1 MB (as small as possible) ]
    • contains rxjs and angular dependencies, not the whole frameworks
  • bundles/app.bundle.js [ size: depends on your project, mine is ~ 0.5 MB ]
    • contains your project

File Structure

  • projectFolder / app / (all components, directives, templates, etc)
  • projectFolder / gulpfile.js

var gulp = require('gulp'),
  tsc = require('gulp-typescript'),
  Builder = require('systemjs-builder'),
  inlineNg2Template = require('gulp-inline-ng2-template');

gulp.task('bundle', ['bundle-app', 'bundle-dependencies'], function(){});

gulp.task('inline-templates', function () {
  return gulp.src('app/**/*.ts')
    .pipe(inlineNg2Template({ useRelativePaths: true, indent: 0, removeLineBreaks: true}))
    .pipe(tsc({
      "target": "ES5",
      "module": "system",
      "moduleResolution": "node",
      "sourceMap": true,
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "removeComments": true,
      "noImplicitAny": false
    }))
    .pipe(gulp.dest('dist/app'));
});

gulp.task('bundle-app', ['inline-templates'], function() {
  // optional constructor options
  // sets the baseURL and loads the configuration file
  var builder = new Builder('', 'dist-systemjs.config.js');

  return builder
    .bundle('dist/app/**/* - [@angular/**/*.js] - [rxjs/**/*.js]', 'bundles/app.bundle.js', { minify: true})
    .then(function() {
      console.log('Build complete');
    })
    .catch(function(err) {
      console.log('Build error');
      console.log(err);
    });
});

gulp.task('bundle-dependencies', ['inline-templates'], function() {
  // optional constructor options
  // sets the baseURL and loads the configuration file
  var builder = new Builder('', 'dist-systemjs.config.js');

  return builder
    .bundle('dist/app/**/*.js - [dist/app/**/*.js]', 'bundles/dependencies.bundle.js', { minify: true})
    .then(function() {
      console.log('Build complete');
    })
    .catch(function(err) {
      console.log('Build error');
      console.log(err);
    });
});
  • projectFolder / package.json (same as Quickstart guide, just shown devDependencies and npm-scripts required to bundle)

{
  "name": "angular2-quickstart",
  "version": "1.0.0",
  "scripts": {
    ***
     "gulp": "gulp",
     "rimraf": "rimraf",
     "bundle": "gulp bundle",
     "postbundle": "rimraf dist"
  },
  "license": "ISC",
  "dependencies": {
    ***
  },
  "devDependencies": {
    "rimraf": "^2.5.2",
    "gulp": "^3.9.1",
    "gulp-typescript": "2.13.6",
    "gulp-inline-ng2-template": "2.0.1",
    "systemjs-builder": "^0.15.16"
  }
}
  • projectFolder / systemjs.config.js (same as Quickstart guide, not available there anymore)

(function(global) {

  // map tells the System loader where to look for things
  var map = {
    'app':                        'app',
    'rxjs':                       'node_modules/rxjs',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    '@angular':                   'node_modules/@angular'
  };

  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'app/boot.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { defaultExtension: 'js' }
  };

  var packageNames = [
    '@angular/common',
    '@angular/compiler',
    '@angular/core',
    '@angular/forms',
    '@angular/http',
    '@angular/platform-browser',
    '@angular/platform-browser-dynamic',
    '@angular/router',
    '@angular/router-deprecated',
    '@angular/testing',
    '@angular/upgrade',
  ];

  // add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' }
  packageNames.forEach(function(pkgName) {
    packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
  });

  var config = {
    map: map,
    packages: packages
  };

  // filterSystemConfig - index.asp's chance to modify config before we register it.
  if (global.filterSystemConfig) { global.filterSystemConfig(config); }

  System.config(config);

})(this);
  • projetcFolder / dist-systemjs.config.js (just shown the difference with systemjs.config.json)

var map = {
    'app':                        'dist/app',
  };
  • projectFolder / index.html (production) - The order of the script tags is critical. Placing the dist-systemjs.config.js tag after the bundle tags would still allow the program to run but the dependency bundle would be ignored and dependencies would be loaded from the node_modules folder.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <base href="/"/>
  <title>Angular</title>
  <link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>

<my-app>
  loading...
</my-app>

<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>

<script src="node_modules/zone.js/dist/zone.min.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.js"></script>

<script src="dist-systemjs.config.js"></script>
<!-- Project Bundles. Note that these have to be loaded AFTER the systemjs.config script -->
<script src="bundles/dependencies.bundle.js"></script>
<script src="bundles/app.bundle.js"></script>

<script>
    System.import('app/boot').catch(function (err) {
      console.error(err);
    });
</script>
</body>
</html>
  • projectFolder / app / boot.ts is where the bootstrap is.

The best I could do yet :)

Igor
  • 60,821
  • 10
  • 100
  • 175
Ankit Singh
  • 24,525
  • 11
  • 66
  • 89
  • 2
    Hi, the gulp script is creating the bundles, but I'm unsure what should be in the boot.ts file? Aren't all the files now in the bundle? Do we execute the bundle? – chrismarx Sep 27 '16 at 14:30
  • `System.import('app/boot')` in index.html is for SystemJS it's the starting point for your app, it's loaded from bundle, you don't need `boot.ts` after bundle – Ankit Singh Sep 29 '16 at 09:35
  • 2
    Huh, I guess I need to try again. I tried switching to builder.buildStatic and got errors from rxjs about not being loaded as a commonjs or amd module. I'll give your suggestion another try – chrismarx Sep 29 '16 at 14:00
  • Is there a way to remove systemjs from the final build? (I would like to have just a simple static script tag with my bundle) – daveoncode Oct 11 '16 at 10:16
  • 1
    I'm also unclear how the bundles actually get used in this setup? I seem to be running into the exact same issues as @chrismarx here. I can create the bundles, but then it seems everything is still being loaded from my transpiled and copied app folder (located at dist/app). If I look in my network panel I can see that my app related files are actually being loaded from there (components, etc), instead of everything app related coming from app.bundle.js. A_Singh, can you share your boot.ts? It seems I'm missing something here and would love some clarification. – jbgarr Nov 09 '16 at 00:39
  • @jbgarr you need to use `dist-systemjs.config.js` in `index.html` in which `app` maps to `dist/app` – Ankit Singh Nov 09 '16 at 05:40
  • 1
    A_Singh, I don't see how that helps. When `inline-templates` is run it inlines the templates then creates a copy of all app folders and files at `dist/app`. Then in `dist-systemjs.config.js` you map `app` to `dist/app` which is a folder that won't exist if you use the `dist` folder as root. Wouldn't you want to run your app from the `dist` folder? And if that's the case, you wouldn't have a `dist` folder nested in the root `dist` folder. I must be missing something else here. Don't you need to tell systemjs to use your bundled files and not the usual files found in the `dist/app` folder? – jbgarr Nov 09 '16 at 17:02
  • Ok, I finally got it figured out... I had some weirdness going on due to the fact that there were multiple `systemjs.config.js` files being referenced in my app. That was all the result of trying too many different bundling approaches. I was actually including one `systemjs.config.js` file already when bundling some core js files like `zone.js` and `reflect.js`. That was throwing all kinds of things off like actually trying to look for files located in a nested `dist/app` folder... The magic of `systemjs` was confusing me as well. – jbgarr Nov 10 '16 at 00:47
  • glad you figured it out :). it's true that `dist/app` does not exist but `system.js` does not go to look for it because we have bundled it in the bundle. – Ankit Singh Nov 10 '16 at 04:29
  • 1
    I'm encountering an issue with your solution, boot is something that does not exist here, and when I replace it by "app" I'va an error "module is not defined". – LoïcR Nov 21 '16 at 13:09
  • In gulpfile it need to be useRelativePaths, not UseRelativePaths (lower case 'u'). https://github.com/ludohenin/gulp-inline-ng2-template/issues/65#issuecomment-263451814 – anysite May 01 '17 at 08:09
  • I can't seem to get the @angular and rxjs dependencies to load from the `dependencies.bundle.js` file at run time, everything else from your answer works great. I can see the `dependencies.bundle.js` loaded in the browser dev console under my sources but the browser console shows all the dependencies being loaded from `node_modules`. Also in the `gulpfile.js` I had to change the exclusions and include the `node_modules/` folder prefix so by `app.bundle.js` would not include the dependencies. Any idea as to where/what I should check? Also thank you for the great answer. – Igor Jul 10 '17 at 13:07
  • you probably forgot to use `dist-systemjs.config.js` instead of `systemjs.config.js`, there is a slight difference in mapping. should fix the problem, i think. ` ` ` ` You're welcome :) – Ankit Singh Jul 11 '17 at 04:49
  • Unfortunately I had that config referenced in the `index.html` file. I have posted the [question on SO ](https://stackoverflow.com/q/45043221/1260204) with all of the details. I hope maybe you have time to shed some light on it for me. Thank you again. – Igor Jul 11 '17 at 19:42
22

Angular 2 with Webpack (without CLI setup)

1- The tutorial by the Angular2 team

The Angular2 team published a tutorial for using Webpack

I created and placed the files from the tutorial in a small GitHub seed project. So you can quickly try the workflow.

Instructions:

  • npm install

  • npm start. For development. This will create a virtual "dist" folder that will be livereloaded at your localhost address.

  • npm run build. For production. "This will create a physical "dist" folder version than can be sent to a webserver. The dist folder is 7.8MB but only 234KB is actually required to load the page in a web browser.

2 - A Webkit starter kit

This Webpack Starter Kit offers some more testing features than the above tutorial and seem quite popular.

Pat M
  • 5,966
  • 7
  • 24
  • 34
  • hi, is it possible to update the seed project with angular 2.1.0? The tutorial is using angular 2.1.0 now. I followed it and could not get it work. The error is http 404 - can't find app.component.html. – heq99 Oct 17 '16 at 22:30
  • I updated to angular 2.1.0 without problem. app.component.html is called from app.component.ts (templateUrl: './app.component.html'). you have both files in the same app folder? – Pat M Oct 22 '16 at 15:31
  • 1
    Tree-shaking, Minification & Gzipping can greatly reduce the size when you go for production. here is an excellent read with example, http://blog.mgechev.com/2016/06/26/tree-shaking-angular2-production-build-rollup-javascript/ – Hamzeen Hameem Jan 12 '17 at 08:40
16

Angular 2 production workflow with SystemJs builder and gulp

Angular.io have quick start tutorial. I copied this tutorial and extended with some simple gulp tasks for bundling everything to dist folder which can be copied to server and work just like that. I tried to optimize everything to work well on Jenkis CI, so node_modules can be cached and don't need to be copied.

Source code with sample app on Github: https://github.com/Anjmao/angular2-production-workflow

Steps to production
  1. Clean typescripts compiled js files and dist folder
  2. Compile typescript files inside app folder
  3. Use SystemJs bundler to bundle everything to dist folder with generated hashes for browser cache refresh
  4. Use gulp-html-replace to replace index.html scripts with bundled versions and copy to dist folder
  5. Copy everything inside assets folder to dist folder

Node: While you always can create your own build process, but I highly recommend to use angular-cli, because it have all needed workflows and it works perfectly now. We are already using it in production and don't have any issues with angular-cli at all.

Andzej Maciusovic
  • 4,306
  • 1
  • 29
  • 40
16

Angular CLI 1.x.x (Works with Angular 4.x.x, 5.x.x)

This supports:

  • Angular 2.x and 4.x
  • Latest Webpack 2.x
  • Angular AoT compiler
  • Routing (normal and lazy)
  • SCSS
  • Custom file bundling (assets)
  • Additional development tools (linter, unit & end-to-end test setups)

Initial Setup

ng new project-name --routing

You can add --style=scss for SASS .scss support.

You can add --ng4 for using Angular 4 instead of Angular 2.

After creating the project, the CLI will automatically run npm install for you. If you want to use Yarn instead, or just want to look at the project skeleton without install, check how to do it here.

Bundle Steps

Inside the project folder:

ng build -prod

At the current version you need to to specify --aot manually, because it can be used in development mode (although that's not practical due to slowness).

This also performs AoT compilation for even smaller bundles (no Angular compiler, instead, generated compiler output). The bundles are much smaller with AoT if you use Angular 4 as the generated code is smaller.
You can test your app with AoT in development mode (sourcemaps, no minification) and AoT by running ng build --aot.

Output

The default output dir is ./dist, although it can be changed in ./angular-cli.json.

Deployable Files

The result of build step is the following:

(Note: <content-hash> refers to hash / fingerprint of the contents of the file that's meant to be a cache busting way, this is possible since Webpack writes the script tags by itself)

  • ./dist/assets
    Files copied as-is from ./src/assets/**
  • ./dist/index.html
    From ./src/index.html, after adding webpack scripts to it
    Source template file is configurable in ./angular-cli.json
  • ./dist/inline.js
    Small webpack loader / polyfill
  • ./dist/main.<content-hash>.bundle.js
    The main .js file containing all the .js scripts generated / imported
  • ./dist/styles.<content-hash>.bundle.js
    When you use Webpack loaders for CSS, which is the CLI way, they are loaded via JS here

In older versions it also created gzipped versions for checking their size, and .map sourcemaps files, but this is no longer happening as people kept asking to remove these.

Other Files

In certain other occasions, you might find other unwanted files/folders:

  • ./out-tsc/
    From ./src/tsconfig.json's outDir
  • ./out-tsc-e2e/
    From ./e2e/tsconfig.json's outDir
  • ./dist/ngfactory/
    From AoT compiler (not configurable without forking the CLI as of beta 16)
Meligy
  • 35,654
  • 11
  • 85
  • 109
  • Is it possible to separate the angular lib and their dependencies from my app? – Dominick Piganell Dec 12 '16 at 21:29
  • Not using the CLI, which is on purpose for tree-shaking to work. That is removing all Angular EcmaScript modules that are not used in your application. There is a plan to disable this in dev mode for speed (they call the libraries loaded as is "DLL"s), but no plan to separate in end result. It should be achievable if you are rolling your own Webpack stuff though without the CLI. – Meligy Dec 12 '16 at 23:32
  • How to check my app using dist folder. How can I host in my web server ? – raj m Jan 27 '17 at 05:25
  • You just copy it to the server. It's plain static website that can be served anyway. If you use routing, you might want to redirect all calls to the HTML file though, for that check Angular deployment docss on server configuration section https://angular.io/docs/ts/latest/guide/deployment.html#!#server-configuration – Meligy Mar 18 '17 at 23:56
  • @Meligy what if I remove `` from the bundles in prod. it may cause problems in getting latest bundle ? – k11k2 Feb 27 '18 at 09:08
  • Yes. There's a build argument to avoid creating them if you want though. It's --output-hashing (aliases: -oh) Values: none, all, media, bundles See https://github.com/angular/angular-cli/wiki/build – Meligy Feb 27 '18 at 14:41
5

As of today I still find the Ahead-of-Time Compilation cookbook as the best recipe for production bundling. You can find it here: https://angular.io/docs/ts/latest/cookbook/aot-compiler.html

My experience with Angular 2 so far is that AoT creates the smallest builds with almost no loading time. And most important as the question here is about - you only need to ship a few files to production.

This seems to be because the Angular compiler will not be shipped with the production builds as the templates are compiled "Ahead of Time". It's also very cool to see your HTML template markup transformed to javascript instructions that would be very hard to reverse engineer into the original HTML.

I've made a simple video where I demonstrate download size, number of files etc. for an Angular 2 app in dev vs AoT build - which you can see here:

https://youtu.be/ZoZDCgQwnmQ

You'll find the source code used in the video here:

https://github.com/fintechneo/angular2-templates

Peter Salomonsen
  • 5,525
  • 2
  • 24
  • 38
3
        **Production build with

         - Angular Rc5
         - Gulp
         - typescripts 
         - systemjs**

        1)con-cat all js files  and css files include on index.html using  "gulp-concat".
          - styles.css (all css concat in this files)
          - shims.js(all js concat in this files)

        2)copy all images and fonts as well as html files  with gulp task to "/dist".

        3)Bundling -minify angular libraries and app components mentioned in systemjs.config.js file.
         Using gulp  'systemjs-builder'

            SystemBuilder = require('systemjs-builder'),
            gulp.task('system-build', ['tsc'], function () {
                var builder = new SystemBuilder();
                return builder.loadConfig('systemjs.config.js')
                    .then(function () {
                        builder.buildStatic('assets', 'dist/app/app_libs_bundle.js')
                    })
                    .then(function () {
                        del('temp')
                    })
            });


    4)Minify bundles  using 'gulp-uglify'

jsMinify = require('gulp-uglify'),

    gulp.task('minify', function () {
        var options = {
            mangle: false
        };
        var js = gulp.src('dist/app/shims.js')
            .pipe(jsMinify())
            .pipe(gulp.dest('dist/app/'));
        var js1 = gulp.src('dist/app/app_libs_bundle.js')
            .pipe(jsMinify(options))
            .pipe(gulp.dest('dist/app/'));
        var css = gulp.src('dist/css/styles.min.css');
        return merge(js,js1, css);
    });

5) In index.html for production 

    <html>
    <head>
        <title>Hello</title>

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta charset="utf-8" />

       <link rel="stylesheet" href="app/css/styles.min.css" />   
       <script type="text/javascript" src="app/shims.js"></script>  
       <base href="/">
    </head>
     <body>
    <my-app>Loading...</my-app>
     <script type="text/javascript" src="app/app_libs_bundle.js"></script> 
    </body>

    </html>

 6) Now just copy your dist folder to '/www' in wamp server node need to copy node_modules in www.
3

ng build --configuration production (angular 14 onwards)

2

You can deploy your angular application on github using angular-cli-ghpages

check out the link to find how to deploy using this cli.

the deployed website will be stored in some branch in github typically

gh-pages

use can clone the git branch and use it like static website in your server

Sunil Kumar
  • 759
  • 7
  • 17
1

"Best" depends on the scenario. There are times when you only care about the smallest possible single bundle, but in large apps you may have to consider lazy loading. At some point it becomes impractical to serve the entire app as a single bundle.

In the latter case Webpack is generally the best way since it supports code splitting.

For a single bundle I would consider Rollup, or the Closure compiler if you are feeling brave :-)

I have created samples of all Angular bundlers I've ever used here: http://www.syntaxsuccess.com/viewarticle/angular-production-builds

The code can be found here: https://github.com/thelgevold/angular-2-samples

Angular version: 4.1.x

TGH
  • 38,769
  • 12
  • 102
  • 135
1

ng serve works for serving our application for development purposes. What about for production? If we look into our package.json file, we can see that there are scripts we can use:

"scripts": {
  "ng": "ng",
  "start": "ng serve",
  "build": "ng build --prod",
  "test": "ng test",
  "lint": "ng lint",
  "e2e": "ng e2e"
},

The build script uses the Angular CLI's ng build with the --prod flag. Let's try that now. We can do it one of two ways:

# using the npm scripts

npm run build

# using the cli directly

ng build --prod

This time we are given four files instead of the five. The --prod flag tells Angular to make our application much smaller in size.

Yogesh Waghmare
  • 941
  • 10
  • 10
0

Just setup angular 4 with webpack 3 within a minute your development and production ENV bundle will become ready without any issue just follow the below github doc

https://github.com/roshan3133/angular2-webpack-starter

Nicolas Henneaux
  • 11,507
  • 11
  • 57
  • 82
AniketGole
  • 889
  • 2
  • 11
  • 22
0

Please try below CLI command in current project directory. It will create dist folder bundle. so you can upload all files within dist folder for deployments.

ng build --prod --aot --base-href.

0

Kindly use the following cmd in your terminal

  ng build --configuration production --aot
codelone
  • 604
  • 8
  • 17