By TEN BITCOMB

How To Add Fonts From NPM To An Ember App

Fonts are still a convenient way of implementing icons in web apps, yet the story around importing fonts from NPM packages in Ember isn't told.

Linking to a CDN is a common solution, but what if I want to host my own fonts? One could easily copy font files to the public/ directory, either by hand or by a custom script. This neither seems particularly Ember-y, and could require multiple steps when installing an updated version of a font's NPM package.

Sadly, this doesn't work:

// ember-cli-build.js
app.import('node_modules/somefont/somefont.ttf');

Ancillary assets such as fonts seem to get the broadside, but I've found a more ideal way to add font files the Broccoli tree when your Ember app builds.

Merging Trees

Install the following packages using NPM:

npm install --save-dev broccoli-funnel broccoli-source broccoli-merge-trees

Inside your ember-cli-build.js file:

// ember-cli-build.js
const EmberApp     = require('ember-cli/lib/broccoli/ember-app'),
      Funnel       = require('broccoli-funnel'),
      UnwatchedDir = require('broccoli-source').UnwatchedDir,
      MergeTrees   = require('broccoli-merge-trees');
module.exports = function(defaults) {
  const app = new EmberApp(defaults, {
  });
  const customIcons = new Funnel(new UnwatchedDir('node_modules/somefont'), {
    destDir: 'assets/fonts/somefont',
    include: ['*.eot', '*.ttf', '*.woff', '*.woff2']
  });
  const tree = MergeTrees([app.toTree(), customIcons]);
  return tree;
};

Then you can reference these fonts in your CSS:

@font-face {  
  font-family: 'Some Font'
  src: url(assets/fonts/somefont/somefont.ttf) format("truetype");
}
.my-font { 
  font-family: Some Font;
}

Using this approach, you can add any file you want to your build output that isn't located in your public/ directory.