• Stars
    star
    1,002
  • Rank 45,804 (Top 1.0 %)
  • Language
    JavaScript
  • License
    Other
  • Created over 9 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Magically generate all the @font-face rules

Font Magician Build Status

Font Magician is a PostCSS plugin that magically generates all of your @font-face rules. Never write a @font-face rule again.

Just use the font and font-family properties as if they were magic.

/* before */

body {
   font-family: "Alice";
}

/* after */

@font-face {
   font-family: "Alice";
   font-style: normal;
   font-weight: 400;
   src: local("Alice"), local("Alice-Regular"),
        url("http://fonts.gstatic.com/s/alice/v7/sZyKh5NKrCk1xkCk_F1S8A.eot?#") format("eot"),
        url("http://fonts.gstatic.com/s/alice/v7/l5RFQT5MQiajQkFxjDLySg.woff2") format("woff2"),
        url("http://fonts.gstatic.com/s/alice/v7/_H4kMcdhHr0B8RDaQcqpTA.woff")  format("woff"),
        url("http://fonts.gstatic.com/s/alice/v7/acf9XsUhgp1k2j79ATk2cw.ttf")   format("truetype")
}

body {
  font-family: "Alice";
}
  • Want to use Google Fonts? I’ll add them for you.
  • Want to use Material Icons?
body {
   font-family: "Material Icons";
}
  • Want to use the visitor’s local copy of a font? Done.
  • Want to host your own fonts? Just tell me where they are, and I’ll do the rest.
  • Want to load a font async and only use it after it has been loaded? I can do that too.
  • Want to use Bootstrap typography? Beautiful, fully-stacked families for serif, sans-serif, and monospace are waiting for you.

Seriously, never write a @font-face rule again.

Need more? Request additional magic by creating an issue.

Installation

Add Font Magician to your build tool.

npm install postcss postcss-font-magician --save-dev

or

yarn add postcss postcss-font-magician --dev

Node

Use Font Magician in your script:

const fs = require('fs');
const postcss = require('postcss');
const pfm = require('postcss-font-magician');
postcss([
   pfm({ /* options */ })
]).process(
   fs.readFileSync('./css/src/style.css', 'utf8')
).then(function (result) {
   fs.writeFileSync('./css/style.css', result.css);
});

Webpack

Use Font Magician in your webpack.config.js:

Webpack 1.x

  postcss: function () {
    return [
      ...
      fontMagician({
          variants: {
              'Roboto Condensed': {
                  '300': [],
                  '400': [],
                  '700': []
              }
          },
          foundries: ['google']
      })
      ...
    ];
}

Webpack 2.x

plugins: [
  new webpack.LoaderOptionsPlugin({
    options: {
      ...
      postcss: [
        ...
        fontMagician({
            variants: {
                'Roboto Condensed': {
                    '300': [],
                    '400': [],
                    '700': []
                }
            },
            foundries: ['google']
        })
      ]
    },
  }),
  ...
]

Webpack 3+

postcss.config.js

module.exports = {
  plugins: {
    'postcss-font-magician': {
         variants: {
             'Roboto Condensed': {
                 '300': [],
                 '400': [],
                 '700': []
             }
         },
         foundries: ['google']
    }
  }
}

webpack.config.js

{
  loader: 'postcss-loader',
  options: {
    config: {
      path: 'path/to/postcss.config.js'
    }
  }
}

Grunt

Use Font Magician in your Gruntfile:

grunt.loadNpmTasks('grunt-postcss');

grunt.initConfig({
   postcss: {
      options: {
         processors: [
            require('postcss-font-magician')({ /* options */ })
         ]
      },
      src: './css/src/*.css',
      dest: './css'
   }
});

Gulp

Use Font Magician in your Gulpfile:

var postcss = require('gulp-postcss');

gulp.task('css', function () {
   return gulp.src('./css/src/*.css').pipe(
      postcss([
         require('postcss-font-magician')({ /* options */ })
      ])
   ).pipe(
      gulp.dest('./css')
   );
});

Options

variants

Want to download only specific font weights, styles and formats?

require('postcss-font-magician')({
   variants: {
                'Open Sans': {
                    '300': ['woff, eot, woff2'],
                    '400 italic': ['woff2']
                }
            }
});

The plugin will download the font only selected weights, styles and formats.

unicode-range

Need to support unicode-range? You can use both the names of the subsets of Google fonts (e.g. 'latin-ext' or 'cyrillic') and specific unicode ranges values. You can use it as a second element in an option array.

require('postcss-font-magician')({
   variants: {
                'Open Sans': {
                    '300': ['woff2', 'cyrillic-ext, greek'],
                    '400 italic': ['woff2', 'U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF']
                }
            }
});

font-stretch

Need to support font-stretch? You can use it as a 2nd or 3rd params in an option key.

require('postcss-font-magician')({
   variants: {
                'Open Sans': {
                    '300 ultra-condenced': ['woff, eot, woff2'],
                    '400 italic': ['woff2'],
                    '400 italic semi-expanded': ['woff2']
                }
            }
});

font-display

Need to control how custom fonts display when they loading? You can use font-display css rule.

require('postcss-font-magician')({
   display: 'swap'
});

hosted

Have a directory of self-hosted fonts?

require('postcss-font-magician')({
   hosted: ['./src/fonts', /custom/path/to/fonts/on/site]
});

The directory will be scanned for font files, which will be read and automatically added if they are used in the document.

Please note that at the moment the plugin doesn't detect woff2 fonts

The first argument of hosted array is required and it should be a path that related to the project root. i.e. ./src/fonts In this case, the path to the fonts folder structure must match the structure of the path to the fonts folder on the server, because the path will be relative css file.

The second argument of hosted array is optional and it can be an arbitrary path which should match the fonts directory on the site. i.e. /assets/fonts

aliases

Prefer another name for particular fonts?

require('postcss-font-magician')({
   aliases: {
      'sans-serif': 'Source Sans Pro'
   }
});

The @font-face rule will be updated so that your alias key is the new name of the font family.

You can also use the 'aliases' option with other options, i.g with the 'variants'

require('postcss-font-magician')({
   aliases: {
      'sans-serif': 'Source Sans Pro'
   },
   variants: {
      'sans-serif': {
          '400': ['woff']
      }
   }
});

async

Need to load the fonts asynchronously?

require('postcss-font-magician')({
   async: 'path/to/your-fonts-async-loader.js'
});

Any @font-face rules are moved out of CSS and into a JavaScript file may be added to a page separately. It will automatically load the fonts before using them.

formats

Want to control which font formats are used?

require('postcss-font-magician')({
   formats: 'woff2 woff'
});

By default, local, woff2, woff, and eot are enabled. Supported formats include local, woff2, woff, ttf, eot, svg, and otf.

foundries

Want to enable specific foundries? Provide a space-separated list or array:

require('postcss-font-magician')({
   foundries: 'bootstrap google'
});

By default, all foundries are enabled. Supported foundries include custom, hosted, bootstrap, and google.

custom

Need something very specific? I can do that, too.

require('postcss-font-magician')({
   custom: {
      'My Special Font': {
         variants: {
            normal: {
               400: {
                  url: {
                     woff2: 'path/to/my-body-font-normal-400.woff2',
                     woff: 'path/to/my-body-font-normal-400.woff'
                  }
               },
               700: {
                  url: {
                     woff2: 'path/to/my-body-font-normal-700.woff2'
                  }
               }
            },
            italic: {
               400: {
                  url: {
                     woff2: 'path/to/my-body-font-italic-400.woff2'
                  }
               }
            }
         }
      }
   }
});

protocol

Do you want to control the font URL-address protocol?

require('postcss-font-magician')({
   protocol: 'https:'
});

By default, 'http/https' protocol is removed from the font url. Supports any string values, eg - '', 'http:' or 'https:'

Future

Look forward to more magic, like:

  • Support for the TypeKit foundry.
  • Option to warn you when unmatched typefaces are used.

Enjoy!

More Repositories

1

sanitize.css

A best-practices CSS foundation
CSS
5,192
star
2

postcss-preset-env

Convert modern CSS into something browsers understand
CSS
2,219
star
3

precss

Use Sass-like markup in your CSS
CSS
1,609
star
4

postcss-plugins

PostCSS Tools and Plugins
CSS
871
star
5

postcss-normalize

Use the parts of normalize.css (or sanitize.css) you need from your browserslist
CSS
816
star
6

postcss-write-svg

Write SVGs directly in CSS
JavaScript
755
star
7

mdcss

Easily create and maintain style guides using CSS comments
JavaScript
686
star
8

cssdb

A database of staged CSS features
JavaScript
522
star
9

system-font-css

Use the native system font of the OS running the browser
HTML
521
star
10

normalize.css

A cross-browser CSS foundation
HTML
473
star
11

postcss-nesting

Nest style rules inside each other
CSS
451
star
12

postcss-custom-media

Use Custom Media Queries in CSS, following the CSS Media Queries specification
JavaScript
438
star
13

postcss-short

Use advanced shorthand properties in CSS
JavaScript
189
star
14

oldie

Compile CSS compatible with old Internet Explorer
JavaScript
168
star
15

postcss-time-machine

Fix mistakes in the design of CSS itself
JavaScript
159
star
16

postcss-logical

Use logical properties and flow-relative values in CSS
JavaScript
137
star
17

postcss-sass

Use Sass as a PostCSS plugin
JavaScript
136
star
18

postcss-custom-selectors

Use Custom Selectors in CSS
JavaScript
131
star
19

postcss-advanced-variables

Use Sass-like variables, conditionals, and iterators in CSS
JavaScript
126
star
20

react-app-rewire-postcss

Configure PostCSS in Create React App without ejecting
JavaScript
114
star
21

css-typed-om

Use CSS Typed Object Model in the browser
JavaScript
101
star
22

css-prefers-color-scheme

Use light or dark color themes in CSS
JavaScript
99
star
23

postcss-color-mod-function

Modify colors using the color-mod() function in CSS
JavaScript
96
star
24

postcss-language

Support for modern and experimental CSS within Visual Studio Code
77
star
25

postcss-partial-import

Inline sugary @import statements in CSS
JavaScript
72
star
26

tokenizer

Tokenize CSS according to the CSS Syntax
TypeScript
67
star
27

parser

CSS Parser
JavaScript
63
star
28

stylelint-value-no-unknown-custom-properties

A stylelint rule to catch usage of unknown custom properties
JavaScript
63
star
29

postcss-conic-gradient

Use conic gradients in your CSS files
JavaScript
60
star
30

postcss-wcag-contrast

Check CSS for WCAG color contrast compliance
JavaScript
59
star
31

postcss-env-function

Use env() variables in CSS
JavaScript
54
star
32

postcss-focus-visible

Use the :focus-visible pseudo-selector in CSS
CSS
53
star
33

postcss-extend-rule

Use the @extend at-rule and functional selectors in CSS
JavaScript
51
star
34

stylelint-use-logical

Enforce usage of logical properties and values in CSS
JavaScript
50
star
35

postcss-selector-not

PostCSS plugin to transform :not() W3C CSS level 4 pseudo class to more compatible CSS (multiple css3 :not() selectors)
JavaScript
48
star
36

postcss-transform-shortcut

Use shorthand transform properties in CSS
JavaScript
48
star
37

postcss-lab-function

Use lab() and lch() color functions in CSS
JavaScript
48
star
38

postcss-input-range

Use unprefixed input range selectors in CSS
JavaScript
42
star
39

stylelint-use-nesting

Enforce nesting when it is possible in CSS
JavaScript
40
star
40

postcss-unmq

Remove media queries from CSS while preserving rules that match a hard-coded viewport
JavaScript
37
star
41

css-has-pseudo

Style elements relative to other elements
JavaScript
35
star
42

postcss-image-set-function

Use image-set() in CSS
CSS
34
star
43

postcss-focus-within

Use the :focus-within pseudo-selector in CSS
CSS
30
star
44

postcss-pseudo-class-enter

Use the :enter pseudo-class in CSS
JavaScript
28
star
45

postcss-is-pseudo-class

Match elements by inner selectors in CSS
JavaScript
27
star
46

postcss-pseudo-class-any-link

Use the :any-link pseudo-class in CSS
JavaScript
24
star
47

postcss-short-size

Use size properties in CSS
JavaScript
21
star
48

postcss-gap-properties

Use the gap, column-gap, and row-gap shorthand properties in CSS
JavaScript
20
star
49

custom-units

Use Custom Units in CSS
JavaScript
18
star
50

postcss-dir-pseudo-class

Use the :dir() pseudo-class to style by directionality in CSS
JavaScript
16
star
51

postcss-media-fn

Use media() to assign responsive values to a property
JavaScript
15
star
52

postcss-font-weights

Use common font weights in CSS
CSS
15
star
53

create-postcss-plugin

Quickly create new PostCSS plugins
JavaScript
15
star
54

postcss-tape

Quickly test PostCSS plugins
JavaScript
15
star
55

super-postcss

Now you’re playing with PostCSS — Super PostCSS!
JavaScript
14
star
56

postcss-register-property

Register properties in CSS
JavaScript
14
star
57

postcss-inset

Use the inset property in CSS
JavaScript
13
star
58

postcss-trig

Use trigonometry functions in CSS
JavaScript
12
star
59

postcss-export-custom-variables

Export custom media queries, custom properties, custom property sets, and custom selectors from CSS to JS
JavaScript
12
star
60

stylelint-media-use-custom-media

Enforce usage of custom media queries in CSS
JavaScript
11
star
61

postcss-at-else

Use at-else inverted media queries in CSS
CSS
11
star
62

postcss-list-style-safari-fix

Remove list styles in CSS without preventing VoiceOver from announcing them in Safari
JavaScript
11
star
63

postcss-resolve-nested-selector

Resolve a nested selector in a PostCSS AST
JavaScript
10
star
64

postcss-place

place-* shorthand for align-* and justify-*
JavaScript
10
star
65

css-blank-pseudo

Style form elements when they are empty
JavaScript
10
star
66

postcss-short-spacing

Omit sides within margin and padding properties in CSS
JavaScript
10
star
67

js-custom-media

Use Custom Media Queries in JS
JavaScript
9
star
68

postcss-browser-comments

Keep only the CSS you need based on comments and your browserslist
CSS
9
star
69

babel-plugin-import-postcss

Import processed CSS files in JS
JavaScript
8
star
70

postcss-to-nest

Transform unnested CSS into nested CSS
JavaScript
8
star
71

css-import-resolve

An algorithm for resolving imports in CSS
JavaScript
8
star
72

postcss-color-functional-notation

Use space and slash separated color notation in CSS
JavaScript
8
star
73

postcss-attribute-case-insensitive

PostCSS plugin to support case insensitive attributes
JavaScript
8
star
74

postcss-custom-utils

Read, write, and transform Custom Media and Custom Properties from almost anywhere
JavaScript
7
star
75

postcss-preset-env-www

The official website for PostCSS Preset Env
HTML
7
star
76

postcss-short-data

Use shorthand data attribute selectors in CSS
JavaScript
7
star
77

postcss-sass-extend

Use @extend and placeholder classes as you would in Sass
JavaScript
6
star
78

postcss-module-import

Inline import statements as CSS Modules
JavaScript
6
star
79

postcss-visitor

Transform CSS with visitor-based plugins
JavaScript
6
star
80

postcss-infrared-filter

Use an infrared photography filter in CSS
JavaScript
6
star
81

postcss-short-position

Define sides within the position property in CSS
JavaScript
6
star
82

postcss-commas

Declare multiple, comma-separated properties
JavaScript
6
star
83

postcss-short-border

Define multiple sides on border properties in CSS
CSS
6
star
84

postcss-double-position-gradients

Use double-position gradients in CSS
JavaScript
6
star
85

stylelint-devtool-prop-order

Enforce CSS property ordering like Chrome DevTools
JavaScript
5
star
86

cccp

Compact Client-side Compatible PostCSS
JavaScript
5
star
87

postcss-short-color

Define background-color within the color property in CSS
JavaScript
5
star
88

postcss-bob-ross-palette

Bring Bob Ross to your CSS :)
JavaScript
5
star
89

postcss-overflow-shorthand

Use the overflow shorthand in CSS
JavaScript
5
star
90

postcss-vmax

Use vmax in Internet Explorer and Edge
JavaScript
5
star
91

postcss-number-functions

Use Sass Number Functions in CSS
JavaScript
5
star
92

postcss-short-font-size

Define line-height within the font-size property in CSS
CSS
4
star
93

create-stylelint-plugin

Quickly create new stylelint plugins
JavaScript
4
star
94

stylelint-color-control

Control color usage in CSS
JavaScript
4
star
95

postcss-unrgba

Convert rgba() values to hex
JavaScript
4
star
96

postcss-short-text

Use a shorthand text property in CSS
JavaScript
4
star
97

postcss-plugins-directory

JavaScript
4
star
98

parse

A tool to read CSS and do things with it in JavaScript
JavaScript
4
star
99

postcss-words

Transform CSS keywords into custom values in CSS
JavaScript
3
star
100

postcss-identifiers

Use identifiers in CSS to write intelligent shorthands
JavaScript
3
star