How do I set the <base> element for a grunt build?
The final app I create will be in / subdirectory on the server.
Setting html5mode to true for angularjs so I lose the # sign works great. But I also need to install
<base href="/subdirectory/"></base>
During development, I cannot have a "base" element, as when running 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 create a grunt build ?
Thank.
source share
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 have defined a custom build block named base
so that it uses "" at design time (or whatever you set there) and to get the value from the build block config.
source share
Please read here . I avoid using the base tag. To solve the problem you have (which I also had), do two things:
-
In index.html, specify the entire js / css path as a relation to the index.html path, so it works like in prod / dev
-
write an http interceptor that, when loading html / api calls, add base to 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, }; } ]);
source share