3

We have some code in Angular JS which is build using gulp (babel). We have necessity to redirect the api service calls to a different server. Hence, which development we run gulp server and with that add the api-host server in the proxy argument while running gulp server, as follows:

gulp serve:dist --mock no --proxy http://<host-name>:8090

Now, after development, we build and distribute the same bundle to different host (not the same host where the api services are hosted). Now we are not able to connect to the api server. The command we use to build is

gulp build:dist --mock no

Even if we add the proxy argument here, it doesn't works.

gulp build:dist --mock no --proxy http://<host-name>:8090

We tried customizing the "gulpfile.babel.js" file. but no result. The following is the "gulpfile.babel.js" used:

'use strict';

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var runSequence = require('run-sequence');
var del = require('del');
var _ = require('lodash');
var historyApiFallback = require('connect-history-api-fallback');
var path = require('path');
var args = require('yargs').argv;
var proxyMiddleware = require('http-proxy-middleware');
var merge = require('merge-stream');

// browserSync
var browserSync = require('browser-sync');
var reload = browserSync.reload;

// config & testing
var config = require('./build/build.config.js');
var protractorConfig = require('./build/protractor.config.js');
var karmaConfig = require('./build/karma.config.js');
var KarmaServer = require('karma').Server;

var pkg = require('./package');

/* jshint camelcase:false*/
var webdriverStandalone = require('gulp-protractor').webdriver_standalone;
var webdriverUpdate = require('gulp-protractor').webdriver_update;
//update webdriver if necessary, this task will be used by e2e task
gulp.task('webdriver:update', webdriverUpdate);

// util functions
function sortModulesFirst(a, b) {
  var module = /\.module\.js$/;
  var aMod = module.test(a.path);
  var bMod = module.test(b.path);
  // inject *.module.js first
  if (aMod === bMod) {
    // either both modules or both non-modules, so just sort normally
    if (a.path < b.path) {
      return -1;
    }
    if (a.path > b.path) {
      return 1;
    }
    return 0;
  } else {
    return (aMod ? -1 : 1);
  }
}

// serve app in dev mode or prod mode
function serverOptions(logPrefix) {
  var proxy = args.proxy;
  var options = {
    notify: false,
    logPrefix: pkg.name,
    server: {
      baseDir: ['build', 'client']
    }
  };

  // use a proxy server to serve '/api/**'' and '/auth' routes
  if (proxy && args.mock === 'no') {
    options.server.middleware = [
      proxyMiddleware(['/auth', '/api'], {
        target: proxy
      }),
      historyApiFallback()
    ];
  } else {
    // use Angular's $httpBackend as the server
    options.server.middleware = [
      historyApiFallback()
    ];
  }

  if (logPrefix) {
    options.logPrefix = pkg.name;
  }

  return options;
}

// run unit tests and watch files
gulp.task('tdd', function(cb) {
  new KarmaServer(_.assign({}, karmaConfig, {
    singleRun: false,
    action: 'watch',
    browsers: ['PhantomJS']
  }), cb).start();
});

// run unit tests with travis CI
gulp.task('travis', ['build'], function(cb) {
  new KarmaServer(_.assign({}, karmaConfig, {
    singleRun: true,
    browsers: ['PhantomJS']
  }), cb).start();
});

// optimize images and put them in the dist folder
gulp.task('images', function() {
  return gulp.src(config.images, {
      base: config.base
    })
    .pipe($.imagemin({
      progressive: true,
      interlaced: true
    }))
    .pipe(gulp.dest(config.dist))
    .pipe($.size({
      title: 'images'
    }));
});

//generate angular templates using html2js
gulp.task('templates', function() {
  return gulp.src(config.tpl)
    .pipe($.changed(config.tmp))
    .pipe($.html2js({
      outputModuleName: 'templates',
      base: 'client',
      useStrict: true
    }))
    .pipe($.concat('templates.js'))
    .pipe(gulp.dest(config.tmp))
    .pipe($.size({
      title: 'templates'
    }));
});

//generate css files from scss sources
gulp.task('sass', function() {
  return gulp.src(config.mainScss)
    .pipe($.sass())
    .pipe($.autoprefixer({
      browsers: ['last 2 versions'],
      cascade: false
    }))
    .on('error', $.sass.logError)
    .pipe(gulp.dest(config.tmp))
    .pipe($.size({
      title: 'sass'
    }));
});

//generate a minified css files, 2 js file, change theirs name to be unique, and generate sourcemaps
gulp.task('html', function() {
  let useminConfig = {
    path: '{build,client}',
    css: [$.csso(), $.rev()],
    vendorJs: [$.uglify({
      mangle: false
    }), $.rev()],
    mainJs: [$.ngAnnotate(), $.uglify({
      mangle: false
    }), $.rev()]
  };

  if (args.mock === 'no') {
    // Don't include mock vendor js
    useminConfig.mockVendorJs = [];

    return gulp.src(config.index)
      .pipe($.usemin(useminConfig))
      .pipe($.replace('<script src="assets/js/mock-vendor.js"></script>', ''))
      .pipe(gulp.dest(config.dist))
      .pipe($.size({
        title: 'html'
      }));
  } else {
    // Include mock vendor js
    useminConfig.mockVendorJs = [$.uglify({
      mangle: false
    }), $.rev()];

    return gulp.src(config.index)
      .pipe($.usemin(useminConfig))
      .pipe(gulp.dest(config.dist))
      .pipe($.size({
        title: 'html'
      }));
  }
});

// clean up mock vendor js
gulp.task('clean:mock', function(cb) {
  if (args.mock === 'no') {
    let paths = [path.join(config.dist, 'assets/js/mock-vendor.js')];
    del(paths).then(() => {
      cb();
    });
  } else {
    cb();
  }
});

//copy assets in dist folder
gulp.task('copy:assets', function() {
  return gulp.src(config.assets, {
      dot: true,
      base: config.base
    })
    //.pipe(gulp.dest(config.dist + '/assets'))
    .pipe(gulp.dest(config.dist))
    .pipe($.size({
      title: 'copy:assets'
    }));
});

//copy assets in dist folder
gulp.task('copy', function() {
  return gulp.src([
      config.base + '/*',
      '!' + config.base + '/*.html',
      '!' + config.base + '/src',
      '!' + config.base + '/test',
      '!' + config.base + '/bower_components'
    ])
    .pipe(gulp.dest(config.dist))
    .pipe($.size({
      title: 'copy'
    }));
});

//clean temporary directories
gulp.task('clean', del.bind(null, [config.dist, config.tmp]));

//lint files
gulp.task('jshint', function() {
  return gulp.src(config.js)
    .pipe(reload({
      stream: true,
      once: true
    }))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// babel
gulp.task('transpile', function() {
  return gulp.src(config.js)
    .pipe($.sourcemaps.init())
    .pipe($.babel({
      presets: ['es2015']
    }))
    .pipe($.sourcemaps.write('.'))
    .pipe(gulp.dest(
      path.join(config.tmp, 'src')
    ));
});

// inject js
gulp.task('inject:js', () => {
  var injectJs = args.mock === 'no' ?
    config.injectJs :
    config.injectJs.concat(config.mockJS);

  return gulp.src(config.index)
    .pipe($.inject(
      gulp
      .src(injectJs, {
        read: false
      })
      .pipe($.sort(sortModulesFirst)), {
        starttag: '<!-- injector:js -->',
        endtag: '<!-- endinjector -->',
        transform: (filepath) => '<script src="' + filepath.replace('/client', 'tmp') + '"></script>'
      }))
    .pipe(gulp.dest(config.base));
});

/** ===================================
  build tasks
======================================*/
//build files for development
gulp.task('build', ['clean'], function(cb) {
  runSequence(['sass', 'templates', 'transpile', 'inject:js'], cb);
});

//build files for creating a dist release
gulp.task('build:dist', ['clean'], function(cb) {
  //runSequence(['jshint', 'build', 'copy', 'copy:assets', 'images', 'test:unit'], 'html', cb);
  runSequence(['jshint', 'build', 'copy', 'copy:assets', 'images'], 'html', 'clean:mock', cb);
});

// For aniden internal usage
// changed app root for labs server
gulp.task('labs:aniden', function() {
  let base = `/hpe/mvno_portal/build/v${pkg.version}/`;

  let html = gulp.src(config.dist + '/index.html', {
      base: config.dist
    })
    .pipe($.replace('<base href="/">', `<base href="${base}">`))
    .pipe(gulp.dest(config.dist));

  let css = gulp.src(config.dist + '/**/*.css', {
      base: config.dist
    })
    .pipe($.replace('url(/', `url(${base}`))
    .pipe($.replace('url("/', `url("${base}`))
    .pipe(gulp.dest(config.dist));

  let js = gulp.src(config.dist + '/**/*.js', {
      base: config.dist
    })
    .pipe($.replace('href="/"', `href="${base}"`))
    .pipe(gulp.dest(config.dist));

  return merge(html, css, js);
});

/** ===================================
  tasks supposed to be public
======================================*/
//default task
gulp.task('default', ['serve']); //

//run unit tests and exit
gulp.task('test:unit', ['build'], function(cb) {
  new KarmaServer(_.assign({}, karmaConfig, {
    singleRun: true
  }), cb).start();
});

// Run e2e tests using protractor, make sure serve task is running.
gulp.task('test:e2e', ['webdriver:update'], function() {
  return gulp.src(protractorConfig.config.specs)
    .pipe($.protractor.protractor({
      configFile: 'build/protractor.config.js'
    }))
    .on('error', function(e) {
      throw e;
    });
});

//run the server,  watch for file changes and redo tests.
gulp.task('serve:tdd', function(cb) {
  runSequence(['serve', 'tdd'], cb);
});

//run the server after having built generated files, and watch for changes
gulp.task('serve', ['build'], function() {
  browserSync(serverOptions());

  gulp.watch(config.html, reload);
  gulp.watch(config.scss, ['sass', reload]);
  gulp.watch(config.js, ['jshint', 'transpile']);
  gulp.watch(config.tpl, ['templates', reload]);
  gulp.watch(config.assets, reload);
});

//run the app packed in the dist folder
gulp.task('serve:dist', ['build:dist'], function() {
  browserSync(serverOptions());
});
indranil9286
  • 81
  • 2
  • 10

1 Answers1

1

You can use gulp-ng-config to add constant in you app module.

Or you a JSON as a config file inside your gulp:

//Gulp file
var fs = require('fs');
var settings = JSON.parse(fs.readFileSync('./config/config.json', 'utf8'));

....

gulp.task('statics', g.serve({
  port: settings.frontend.ports.development,
  ...  
}));

gulp.task('production', g.serve({
  port: settings.frontend.ports.production,
  root: ['./dist'],
  ...
}));
Makah
  • 4,435
  • 3
  • 47
  • 68