Search code examples
angulargulpproduction

How to correctly bundle an Angular2-JS/Typescript app via Gulp?


Note: I know there are several similar questions (and the repository mentioned here comes from one of those) but I still don't understand what's not working

Specifically I tried to replicate the logic of the simple app at: https://github.com/templth/angular2-packaging

The issue is (see my Gulp config file below) that I get only 3 files in ./dist:

  • app.min.js <-- this is just a 9-line lines code (and my app is way more complex) containing: var __decorate = (this && this.__decorate) || ...
  • index.html <-- this seems "complete"
  • vendors.ts <-- this seems "complete"

What happens is that the app just shows "Loading...", no error and If I go to "sources" (Chrome dev tools) I see nothing is really loaded (except the 3 files above as I see them in ./dist directory)

I also tried:

  • to bypass Typescript and just bundle JS file but what happens is that all the files are there, but I get
  • without uglification

require is not defined

My Gulp config file

'use strict';

const gulp = require('gulp');
const ts = require('gulp-typescript');
const uglify = require('gulp-uglify');
const concat = require('gulp-concat');
var htmlreplace = require('gulp-html-replace');
var addsrc = require('gulp-add-src');

gulp.task('app-bundle', function () {
    var tsProject = ts.createProject('tsconfig.json', {
        typescript: require('typescript'),
        outFile: 'app.js'
    });

    var tsResult = gulp.src([
        'node_modules/**/*.ts.d',
        'typings/**/*.ts.d',
        'app/**/*.ts'
    ]).pipe(ts(tsProject));

    return tsResult.js
        .pipe(addsrc.append('config-prod.js'))
        .pipe(concat('app.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('./dist'));
});

gulp.task('vendor-bundle', function() {
    gulp.src([
        'node_modules/core-js/client/shim.min.js',
        'node_modules/zone.js/dist/zone.js',
        'node_modules/reflect-metadata/Reflect.js',
        'node_modules/systemjs/dist/system.src.js'
    ])
        .pipe(concat('vendors.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('./dist'));
});

gulp.task('html-replace',[ 'app-bundle', 'vendor-bundle' ], function() {
    gulp.src('index.html')
        .pipe(htmlreplace({
            'vendor': 'vendors.min.js',
            'app': 'app.min.js'
        }))
        .pipe(gulp.dest('dist'));
});

// define which tasks should Gulp launch
gulp.task('default', ['app-bundle', 'vendor-bundle','html-replace']);

Solution

  • You should use special gulp module called "systemjs builder". Also you should use compile parameter in tsconfig.js as "commonjs". Moreover it's should be npm references included in that file. All of that should solve your issue.