Angular 2 base href from environment variable

I would like to have a different base link in my Angular 2 app for developers and for production.

I saw answers to questions that are similar (and some are identical) to this one.

The best answer here summarizes 2 solutions that are repeated in all answers to these questions:

Set base href from environment variable with ng build

I tried both, each has its own problems:

1) APP_BASE_HREF- does not work with js / css files. For example, when trying to request app / someroute / 1 , it will try to request js and css files from app / someroute / 1, and not from the application.

2) Modification of base href in ngOnInit- by the time it is called ngOnInit, the js and css files have already been requested, and therefore the changed base href does not apply to files loaded in init, only to files requested later (which does not help me).

The only thing that still works for me is to manually change the html for production after each compilation, but I'm trying to automate it.

Possible solutions:

1) Changing base href before requesting js and css files - is there any way to do this? They are mostly requested immediately when the page loads. Perhaps adding scripts that are executed in the head before the rel link?

2) Compilation of different HTML codes for dev and production with different base href values, for example with some very light HTML template engine, which will not be redundant.

What do you think?

+4
2

cli ( ) --base-href.

:

ng build --prod --base-href=/prod_dir/

+7

Gulp 4 Angular -cli. Gulp cli . ( gulp -rsync).

gulpfile:

const spawn = require('child_process').spawn;
const environment = process.env.NODE_ENV || 'staging';

if (environment === 'development') {
  console.log('No deploys performed for development environment.');
  process.exit(0);
}

gulp.task('build', gulp.series(build));

function build(done) {
  var cmd = spawn('ng', ['build', '--target=production', '--environment=' + environment, '--base-href=/app/'], {stdio: 'inherit'});
  cmd.on('close', function (code) {
    console.log('Build task exited with code: ' + code);
    done(code);
  });
}
0

Source: https://habr.com/ru/post/1670831/


All Articles