Search code examples
javascriptfont-awesomeaurelia

How can I add Font Awesome to my Aurelia project using npm?


I have been following the Contact Manager tutorial and would like to add Font Awesome to the project. Here's what I have done so far:

  • npm install Font-Awesome --save
  • Added the following to aurelia.jsonunder the dependencies array of the vendor-bundle.js:


...
{
    "name": "font-awesome",
    "path": "../node_modules/font-awesome",
    "resources": [
      "css/font-awesome.min.css"
    ]
},
...

But when running au run --watch I get the error:

error C:\Users\node_modules\font-awesome.js

Why is it looking for the .js file?


Solution

  • Don't add font-awesome resources to aurelia.json - you'd need font files too, which Aurelia don't process. Instead, take the following steps.

    First, if you added anything for font-awesome already to your aurelia.json file, remove it again.

    Add new file prepare-font-awesome.js in folder \aurelia_project\tasks and insert the below code. It copies font-awesome resource files to output folder (as configured aurelia.json config file; e.g. scripts):

    import gulp from 'gulp';
    import merge from 'merge-stream';
    import changedInPlace from 'gulp-changed-in-place';
    import project from '../aurelia.json';
    
    export default function prepareFontAwesome() {
      const source = 'node_modules/font-awesome';
    
      const taskCss = gulp.src(`${source}/css/font-awesome.min.css`)
        .pipe(changedInPlace({ firstPass: true }))
        .pipe(gulp.dest(`${project.platform.output}/css`));
    
      const taskFonts = gulp.src(`${source}/fonts/*`)
        .pipe(changedInPlace({ firstPass: true }))
        .pipe(gulp.dest(`${project.platform.output}/fonts`));
    
      return merge(taskCss, taskFonts);
    }
    

    Open the build.js file in the \aurelia_project\tasks folder and insert the following two lines; this will import the new function and execute it:

    import prepareFontAwesome from './prepare-font-awesome'; // Our custom task
    
    export default gulp.series(
      readProjectConfiguration,
      gulp.parallel(
        transpile,
        processMarkup,
        processCSS,
        prepareFontAwesome // Our custom task
      ),
      writeBundles
    );
    

    Finally, in the <head> section of your index.html file, just add the following line:

    <link rel="stylesheet" href="scripts/css/font-awesome.min.css">
    

    That's all; now you can use font-awesome icons in any Aurelia view modules (html files).

    Note that this works for any complex third party library which requires resources which you have to manually include.