Socket
Socket
Sign inDemoInstall

@fortawesome/fontawesome

Package Overview
Dependencies
Maintainers
1
Versions
43
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@fortawesome/fontawesome


Version published
Maintainers
1
Created
Source

Font Awesome 5

FontAwesome.js - ES6, CommonJS, and AMD module

"I came here to chew bubblegum and install Font Awesome 5 - and I'm all out of bubblegum"

npm linking

While we are in are Beta period we won't be publishing packages to npmjs.com.

Instead we are going to recommend linking.

The basic steps of this:

  1. Clone the Font-Awesome-Pro repository
  2. Tell npm (or yarn) where the packages are
  3. Link to the packages in your project
Example

Let's say that we've cloned the repository to ~/Development/projects/FortAwesome/Font-Awesome-Pro.

And let's say that we have a project we'd like to use Font Awesome 5 Pro on in ~/Development/projects/myorg/myapp.

Tell npm (or yarn) where the packages are
$ cd ~/Development/projects/FortAwesome/Font-Awesome-Pro/packages/fontawesome
$ npm link
$ cd ~/Development/projects/FortAwesome/Font-Awesome-Pro/packages/fontawesome-solid
$ npm link

If you want the Regular, Light, or Brands styles change directories to those packages and do the same npm link.

$ cd ~/Development/projects/myorg/myapp
$ npm link @fortawesome/fontawesome
$ npm link @fortawesome/fontawesome-solid

Copying the packages to your project

Using npm link is convenient when the project you are linking to changes often and you want to easily keep up. It however is not convenient if you are on a team and sharing a repository with someone else or you have a continuous integration or continuous delivery service. In these cases the build will fail when any dependency on @fortawesome/fontawesome packages are imported in your app since the linking is not part of the normal npm install or yarn install process.

An alternative to linking is to include the packages in your own project.

Example

Let's assume all your app's JavaScript is in src/js.

$ cd ~/Development/projects/myorg/myapp
$ cp ~/Development/projects/FortAwesome/Font-Awesome-Pro/packages/fontawesome/index.js ./src/js/fontawesome.js
$ cp ~/Development/projects/FortAwesome/Font-Awesome-Pro/packages/fontawesome-solid/index.js ./src/js/fontawesome-solid.js

This is kinda gross but until we get packaging setup for our Pro users this will get you by.

Let's get started

Once you have the packages installed (make sure you get fontawesome and at least one of the styles) you can require or import the library. We're going to give examples in ES6 syntax using import.

import fontawesome from '@fortawesome/fontawesome'
import { faUser } from '@fortawesome/fontawesome'

fontawesome.icon(faUser)

See the API reference for more information on what API is available.

Icon naming

From the beginning Font Awesome has used hyphenated names like fa-address-book, fa-facebook, or fa-circle-o.

JavaScript does not typically use this kind of naming scheme; it uses camelCase. So here are some basic examples of how imports will work.

  • fa-address-book becomes import { faAddressBook } from '@fortawesome/fontawesome-solid'
  • fa-facebook becomes import { faFacebookF } from '@fortawesome/fontawesome-brands' (it's in the Brands style and this was renamed to facebook-f)
  • fa-circle-o becomes import { faCircle } from '@fortawesome/fontawesome-regular' (the outlines are in the Regular style)
  • fa-area-chart becomes import { faChartArea } from '@fortawesome/fontawesome-regular' (this was renamed)
  • fa-freebsd becomes import { faFreebsd } from '@fortawesome/fontawesome-brands' (OCD-warning: we know it's FreeBSD but consistency/guessability is the goal here)

Configuration

Font Awesome 5 has several configuration options that affect how the library operates.

Make sure you set your config as early as possible when using automatic CSS inserting (more on this later)

In a browser the config is exported to window.FontAwesomeConfig.

Access the configuration in your app with:

import fontawesome from '@fortawesome/fontawesome'

fontawesome.config

To update the configuration:

import fontawesome from '@fortawesome/fontawesome'

fontawesome.config = {
  familyPrefix: 'fa'
}

There is no need to send every possible config value when updating the config. Properties will be merged with the existing properties and values.

Options

familyPrefix default fa

  • String used to prefix classes like fa-spin. Changing this would allow you to still use Font Awesome 4 with the prefix of fa.

replacementClass default svg-inline--fa

  • String used as the base class name when building the SVG elements. If you changed this to foo the SVGs would start with <svg class="foo ...">.

autoAddCss default true

  • Boolean if this is set to true Font Awesome will automatically add CSS definitions to the <head> of the document.

autoA11y default true

  • Boolean whether to automatically apply accessibility best practices for the generated icons.

measurePerformance default false

  • Boolean setting this to true will add performance markers using the Performance API

The following are not used in the Node.js packages:

  • autoReplaceSvg
  • observeMutations
  • keepOriginalSource
  • showMissingIcons

API reference

fontawesome.dom.i2svg(params)

Will automatically find any <i> tags in the page and replace those with <svg> elements.

This functionality use requestAnimationFrame to batch the updates and increase performance.

Note that this function requires that the packs (located in js/packs) be loaded.

index.html

<head>
  <script src="js/packs/solid.js"></script>
  <script src="bundle.js"></script>
</head>

<i class="fa fa-user"></i>

bundle.js

import fontawesome from '@fortawesome/fontawesome'

fontawesome.dom.i2svg()

To specify a different element to search:

fontawesome.dom.i2svg({ node: document.getElementById('content') })

Register a callback that will be triggered when the icons have been rendered:

function iconDoneRendering () {
  console.log('Icons have rendered')
}

fontawesome.dom.i2svg({ callback: iconsDoneRendering })

fontawesome.dom.styles()

Generates the accompanying CSS that is necessary to correctly display icons. If you choose to disable autoAddCss in the configuration you'll need to grab these styles and insert them manually into the DOM.


fontawesome.dom.insertStyles()

Convenience method that will add the given CSS to the DOM.

const styles = fontawesome.dom.styles()

fontawesome.dom.insertStyles(styles)

fontawesome.parse.transform(transformString)

Takes a Power Transform string like grow-2 left-4 rotate-15 and produces the transform object used to specify transforms in the API.

fontawesome.parse.transform('grow-2 left-4 rotate-15')
{
  "size": 18,
  "x": -4,
  "y": 0,
  "flipX": false,
  "flipY": false,
  "rotate": 15
}

fontawesome.parse.iconFromPack(iconString)

Takes the class portion of an icon's definition and fetches the icon from pack definitions.

Note the icon pack js/packs must be loaded for this function to return anything meaningful.

fontawesome.parse.iconFromPack('fa fa-user')
{
  "prefix": "fa",
  "iconName": "user",
  "icon": [
    512,
    512,
    [],
    "f007",
    "M962…-112z"
  ]
}

You can then feed this as the iconDefinition to other functions.


fontawesome.icon(iconDefinition, params)

Renders an icon as inline SVG.

Simple:

import fontawesome from '@fortawesome/fontawesome'
import { faPlus } from '@fortaewsome/fontawesome-solid'

const faPlusIcon = fontawesome.icon(faPlus)

Getting the HTML for the icon:

fontawesome.icon(faPlus).html
[
  "<svg data-prefix=\"fa\" data-icon=\"user\" class=\"svg-inline--fa fa-user fa-w-16\" …>…</svg>"
]

Appending nodes from an HTMLCollection:

const faPlusIcon = fontawesome.icon(faPlus)

// Get the first element out of the HTMLCollection
document.appendChild(faPlusIcon.node[0])

Abstract tree:

Note the abstract value is mostly useful for library / framework / tooling creators. It provides a data structure that can easily be converted into other objects.

fontawesome.icon(faPlus).abstract
[
  {
    "tag": "svg",
    "attributes": {
      "data-prefix": "fa",
      "data-icon": "user",
      "class": "svg-inline--fa fa-user fa-w-16",
      "role": "img",
      "xmlns": "http://www.w3.org/2000/svg",
      "viewBox": "0 0 512 512"
    },
    "children": [
      {
        "tag": "path",
        "attributes": {
          "fill": "currentColor",
          "d": "M96…112z"
        }
      }
    ]
  }
]

Using a transform:

fontawesome.icon(faPlus, {
  transform: {
    size: 8,     // starts at 16 so this if half
    x: -4,       // the same as left-4
    y: 6,        // the same as up-6
    rotate: 90,  // the same as rotate-90
    flipX: true, // the same as flip-h
    flipY: true  // the same as flip-v
  }
}).html

If you need help figuring out what the transform use fontawesome.parse.transform.

Compose another icon with the main icon:

import { faPlus, faCircle } from '@fortawesome/fontawesome-solid'

fontawesome.icon(faPlus, {
  compose: faCircle
}).html

Add title attribute:

fontawesome.icon(faBars, {
  title: 'Navigation menu'
}).html
[
  "<svg aria-labelledby=\"svg-inline--fa-title-9\" data-prefix=\"fa\" data-icon=\"bars\" class=\"svg-inline--fa fa-bars fa-w-14\" role=\"img\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 448 512\" >" +
    "<title id=\"svg-inline--fa-title-9\" >Navigation menu</title>" +
    "<path …></path>" +
  "</svg>"
]

Additional classes:

fontawesome.icon(faSpinner, {
  classes: ['fa-spin']
}).html
[
  "<svg data-prefix=\"fa\" data-icon=\"spinner\" class=\"svg-inline--fa fa-spinner fa-w-16 fa-spin\" …>…</svg>"
]

Additional attributes:

fontawesome.icon(faSpinner, {
  attributes: { 'data-component-id': 987654 }
}).html

Additional styles:

fontawesome.icon(faSpinner, {
  style: { 'background-color': 'coral' }
}).html

fontawesome.layer(assembler)

Allows multiple icons to be assembled together.

fontawesome.layer((push) => {
  push(fontawesome.icon(faSpinner))
  push(fontawesome.icon(faUser, { transform: { size: 4 } } ))
}).html

fontawesome.text(content, params)

Add text to layers.

fontawesome.layer((push) => {
  push(fontawesome.icon(faSpinner))
  push(fontawesome.text('Wait…', { transform: { size: 4 } } ))
}).html

params allow the following keys:

  • transform
  • title
  • classes
  • attributes
  • style

Using the browser JavaScript file to access the API

The js/fontawesome.js is primarily used for simpler integration with Font Awesome.

By default it will automatically do the following for you:

  1. Search the page for any <i> elements and replace them with inline SVG
  2. Configure a mutation observer that will watch the page for changes and replace with inline SVG

Another thing that it does is make the API available from the global Window object.

window.FontAwesome

You can use it just like you would the Node.js package:

faUser = FontAwesome.parse.iconFromPack('fa fa-user')

FontAwesome.icon(faUser).html

If you would like to disable automatic replacement of <i> tags set the configuration before you load Font Awesome.

<head>
  <script>
  window.FontAwesomeConfig = {
    autoReplaceSvg: false,
  }
  </script>
  <script src="js/fontawesome.js"></script>
  <script src="js/packs/fontawesome-solid.js"></script>
</head>

Automatic CSS inserting

By default the API will automatically insert the needed CSS styles into the <head> of the document.

If you don't like this behaviour see the Configuration section and the autoAddCss property.

Tree shaking (or automatic subsetting)

Beginning with the excellent tool Rollup.js by Rich Harris the concept of tree shaking attempts to eliminate any unused code. Webpack 2 now includes this as well.

FontAwesome.js supports tree shaking and the design of the icon system encourages only importing those icons that you need.

This can result in significantly reduce the bundle size.

FAQs

Package last updated on 18 Aug 2017

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc