Search code examples
angularjsgruntjsboweryeoman-generator

Can I change what path gets rendered when using bower in an yeoman angular app?


I am using html5mode in my angular app, but when I run bower install with grunt, it renders the paths as

<script src="bower_components/...

Can I change this to

<script src="/bower_components/...?

I've added a <base href="/"> tag to my <head/> section, but when my pages try to load javascript, they are still looking for relative urls.

So for a script at /bower_components/script.js, currently rendered as <script src="bower_components/script.js"></script>,

when on /login, the page tries to load /login/bower_components/script.js

EDIT Following @sharpper's advice, I added the code block below and ended up with this in Gruntfile.js:

// Automatically inject Bower components into the app
'bower-install': {
  app: {
    html: '<%= yeoman.app %>/index.html',
    ignorePath: '<%= yeoman.app %>/',
    fileTypes: {
      html: {
        block: /(([\s\t]*)<!--\s*bower:*(\S*)\s*-->)(\n|\r|.)*?(<!--\s*endbower\s*-->)/gi,
        detect: {
          js: /<script.*src=['"](.+)['"]>/gi,
          css: /<link.*href=['"](.+)['"]/gi
        },
        replace: {
          js: '<script src="/{{filePath}}"></script>', // <-- Change this line
          css: '<link rel="/stylesheet" href="{{filePath}}" />'
        }
      },
      yml: {
        block: /(([\s\t]*)#\s*bower:*(\S*)\s*)(\n|\r|.)*?(#\s*endbower\s*)/gi,
        detect: {
          js: /-\s(.+)/gi,
          css: /-\s(.+)/gi
        },
        replace: {
          js: '- {{filePath}}',
          css: '- {{filePath}}'
        }
      }
    }
  }
},

It still compiles correctly, but the files are rendered the same.


Solution

  • Firstly, make sure your bower-install at the latest version: v0.8.0 (yeoman is using v0.7.0 currently), then the code below should work:

         'bower-install': {
             app: {
                src: ['<%= yeoman.app %>/index.html'],
                ignorePath: '<%= yeoman.app %>/',
                fileTypes: {
                    html: {
                        replace: {
                            js: '<script src="/{{filePath}}"></script>',
                            css: '<link rel="stylesheet" href="/{{filePath}}" />'
                        }
                    }
                }
            }
         }
    

    If you don't want to update or this method does not work, try this trick: Change ignorePath: '<%= yeoman.app %>/', to ignorePath: '<%= yeoman.app %>', , then it should work for your purpose.