Search code examples
laravelangularwebpackassetsrelative-path

Angular 2 base_href linking assets issue


I am using laravel 5.3 with angular 2 for my project and using webpack for compilation of the assets including js and css.

I am trying to use same font awesome and bootstrap for the client and admin area.

I have the folder structure of laravel with everything inside js directory.

|-public
   |-js
      |-assets
         |-fontawesome-webfonts.woff
         |-image1.png
      |-vendor.bundle.js
      |-polyfill.bundle.js

For Angular 2 routes we need to add the base href to the main template which i have also added.

<base href="/">

Admin url is localhost:8000/admin

and user url is localhost:8000

I have included the bundles like

{!! Html::script('js/vendor.bundle.js') !!}

and the vendor have imported the less files as:

vendor.bundle.js

import  'admin-lte/build/less/AdminLTE.less';
import  'font-awesome/less/font-awesome.less';

The main issue is that when i use the same vendor.bundle.js to both user and admin pages the user page works fine since it loads the fonts from js/assets/fontawesome-webfonts.woff but when i load the admin page it couldn't load the fonts as it searches from admin/js/assets/fontawesome-webfonts.woff which is not the correct directory.

How could i make Angular search into js/assets/fontawesome-webfonts.woff for both url?

The issue is displayed in the image too.

Assets linking issue


Solution

  • I just figured it out by myself using the url-loader webpack plugin.

    You should leave the base href to as it is and configure the assets.

    I just needed to add a new test only for the fonts

    {
        test: /\.(svg|woff|woff2|ttf|eot)$/,
        loader: 'url-loader?limit=10000&name=assets/[hash].[ext]&publicPath=/js/'
    }
    

    You need to specify the publicPath and add the other directories to name.

    That's all. Hope it will save someone's precious time.

    Note: don't forget the '/' at the front of the public path