Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify base href for scripts and styles in Angular 2?

I'm currently digging into Angular 2 and I'm having a problem with how styles and scripts are injected into index.html by the angular CLI build command (by that I mean scripts and styles defined within angular-cli.json).

The problem is that I'm running the app on a nested location, e.g.: http://domain.com/my_app While <base href="/my_app"> can be set, the injected scripts and styles always point in src to the root domain. i.e. / instead of /my_app. This, of course, results in 404s while trying to view the page.

I'm serving the /dist directly.

Nginx conf:

server {
    server_name domain.com;
    listen 80;

    location /my_app {
            alias /srv/www/my_app;
            index index.html;
            try_files $uri$args $uri$args/ $uri $uri/ /index.html =404;
            gzip on;
            gzip_types text/css text/javascript application/x-javascript application/json;
    }

Where /srv/www/my_app consists of what essentailly /dist contains after running:

ng build --environment=prod --base-href /my_app

I can add prefix manually to styles and scripts declarations within the output index.html but that just seems to me as an unnecessary busywork.

Is there a way to specify the base href for injected styles and scripts declarations within ng build generated index.html? It would be even nicer if I could specify base href based on target environment, e.g.:

  • /my_app for production
  • / for development
like image 999
NullThePointer Avatar asked Dec 02 '16 15:12

NullThePointer


1 Answers

Did you try to use the --deploy-url parameter when executing the ng build command ? This option indicates the URL where files will be deployed

So in your case you can try to run the following command:

ng build --environment=prod --base-href my_app --deploy-url my_app

like image 184
Stéphane Eintrazi Avatar answered Oct 17 '22 22:10

Stéphane Eintrazi