I'm trying to add font-awesome to my Next.js project using webpack. I've tried following various instructions I've found on the web (using file-loader, url-loader), but nothing has worked for me. I gave up loading font-awesome with webpack for the moment, but I want to know how I can accomplish this. Currently, I have a .scss
file that I use to load font-awesome.
It's contents:
$fa-font-path: "static/fonts";
@import "~font-awesome/scss/font-awesome.scss";
And I'm manually moving the fonts from node_modules/font-awesome/fonts
to static/fonts
. This works perfectly, But I wanted to know if there's a webpack 2 way to do it in 2017.
We first have to add the package to our project by running the following command in your project folder to get started. Then we can get started by importing the icons. Head over to the React icons website and find the icon you would like to use (use the left-hand search).
Font Awesome works well with Require. js, especially if you are using Web Fonts.
For anyone who'd like to see a real example with Next 9, check out https://github.com/UnlyEd/next-right-now
Interesting parts are:
Disclaimer: I'm a contributor to the project
Config: pages/_app.tsx
import { config, library } from '@fortawesome/fontawesome-svg-core';
import '@fortawesome/fontawesome-svg-core/styles.css';
import { faGithub } from '@fortawesome/free-brands-svg-icons';
import { faAngleDown } from '@fortawesome/pro-solid-svg-icons';
// See https://github.com/FortAwesome/react-fontawesome#integrating-with-other-tools-and-frameworks
config.autoAddCss = false; // Tell Font Awesome to skip adding the CSS automatically since it's being imported above
library.add(
faGithub, faAngleDown
);
You can use solid/light/etc by importing the icon from the right repository
Usage: components/Nav.tsx
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
<FontAwesomeIcon icon={['fab', 'github']} />
Edit Next.js 10:
While the above still works, what I recommend now for Next.js 10 and higher is to split your Font-Awesome related config into a different file, and import that file in _app.tsx
. This makes the code more maintainable, that's all.
Something like:
There are a few ways to do this. The first would be to create a head component via next/head and import there - see here:
Another way is to create a HOC to wrap your pages with and import there with a simple import 'font-awesome/css/font-awesome.min.css'
Or, you could just import it into one of your page's with the same kind of import. (I believe this will scope it to that particular page however. Double check me on that)
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With