magician11
magician11

Reputation: 4584

How do I set the <base> element for a grunt build?

The final app I'm building will live at /subdirectory on a server.

Setting html5mode to true for angularjs so I lose the # sign works fine. But I also need to set

<base href="/subdirectory/"></base>

During development, I can't have the 'base' element set as when I run grunt serve the server cannot find most of the files.

What is the best way to develop and then maybe set the 'base' element when I do a grunt build ?

Thanks.

Upvotes: 3

Views: 1376

Answers (3)

harishr
harishr

Reputation: 18055

Please read here. I avoid using base tag. To solve the problem you have (which I also had) please do two things:

  1. In index.html specify all js/css path as relation to index.html path, so it works in both prod/dev

  2. write an http interceptor which while loading html/api calls append the base to the url

    myapp.factory('MyHttpInterceptor',[ "$log", function ($log) {
    
        var requestInterceptor = function (config) {
            var prefix = document.location.pathname.substring(0, document.location.pathname.length - 1);
            if (config.url.indexOf(".html") !== -1) {
                config.url = prefix + config.url;
            }
            if (config.url.indexOf("/api/") !== -1) {
                config.url = prefix + config.url;
            }
            return config || $q.when(config);
        };
    
        return {
            request: requestInterceptor,
        };
    }
      ]);
    

Upvotes: 0

roberkules
roberkules

Reputation: 6605

I used the grunt task usemin:

index.html

<!-- build:base /subdirectory/ -->
<base href="">
<!-- endbuild -->

Gruntfile.js

usemin: {
    html: ['<%= yeoman.dist %>/{,*/}*.html'],
    css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
    options: {
        dirs: ['<%= yeoman.dist %>'],
        blockReplacements: {
            base: function (block) {
                return ['<base href="', block.dest, '">'].join('');
            }
        }
    }
}

Basically I defined a custom build block named base and this way it's using "" during development (or whatever you set there) and for production the value from the build block config.

Upvotes: 6

Harutyun Abgaryan
Harutyun Abgaryan

Reputation: 2023

Use in inside head tag <base href="/your MainDomain Name">

<head>
  <meta charset="utf-8">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width">

  <base href="/your MainDomain Name">
</head>

Upvotes: -1

Related Questions