Skip to content

Favicons

Automatically generate favicons for your website

I would suggest reading this article too: How to Favicon in 2021: Six files that fit most needs, to ensure you generate only what you need.

Build pipeline

NPM
package.json
scripts: {
  ...
  "build:dir": "mkdirp ./public/icons/",
  "build:favicons": "node scripts/favicons",
  "build": "npm run build:dir && npm run build:favicons && gatsby build",
}

Use

Using itgalaxy/favicons

JavaScript
scripts/favicons.js
const favicons = require('favicons');
const path = require('path');
const fs = require('fs');
 
// Provide these
const {siteTitleShort, themeColor, backgroundColor} = require('../site-config');
 
const dir = path.resolve(__dirname, '../public/icons/');
if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir);
}
 
// Provide the main icon, in high resolution
const source = 'src/images/icon.png';
const configuration = {
  path: '/icons/',
  appName: siteTitleShort,
  appDescription: null,
  developerName: null,
  developerURL: null,
  dir: 'auto',
  lang: 'en-US',
  background: backgroundColor,
  theme_color: themeColor,
  display: 'standalone',
  orientation: 'any',
  start_url: '/',
  version: '1.0',
  logging: true,
  icons: {
    android: true,
    appleIcon: true,
    appleStartup: true,
    coast: false,
    favicons: true,
    firefox: false,
    windows: true,
    yandex: false,
  },
};
 
const callback = function (err, res) {
  if (err) {
    console.log(err.message);
    return;
  }
 
  res.images.forEach((image) => {
    fs.writeFile(
      path.resolve(__dirname, '../public/icons/', image.name),
      image.contents,
      (err) => {
        if (err) {
          console.log(err);
        }
      }
    );
  });
 
  res.files.forEach((file) => {
    fs.writeFile(
      path.resolve(__dirname, '../public/', file.name),
      file.contents,
      (err) => {
        if (err) {
          console.log(err);
        }
      }
    );
  });
};
 
// start the work
favicons(source, configuration, callback);

Feel happy that you're not using an online tool.