Angular 4: Use of base-href and deploy-url build options


I use Angular 4 at work for building a single page application. Today, I faced the problem where I had to use different base paths for router and static assets. Angular makes use of the base href to tell router how to compose navigation URLs. If your application exists at the root, then you can use / as the href value as shown below.

<base href="/">

I wanted to use /users as my application base for router and /public as base for my assets.

If you build the project the Angular project for the production environment using the default values you will get the following index.html generated.

$ ng build -prod
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>SampleNgApp</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="styles.xxxx.bundle.css" rel="stylesheet"/></head>
<body>
  <app-root>Loading...</app-root>
</body>
</html>

This generated page will not work as it router will use / as base for composing navigation URLs and static assets will be looked in the current directory.

To solve my problem, I used —-base-href and —-deploy-url options as shown below.

$ ng build -prod --base-href /users --deploy-url /public
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>SampleNgApp</title>
  <base href="/users">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="/public/styles.xxxx.bundle.css" rel="stylesheet"/></head>
<body>
  <app-root>Loading...</app-root>
</body>
</html>

This way I solved my problem.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s