LoginSignup
5
2

More than 3 years have passed since last update.

Nuxt.jsでAdobe Fonts(TypeKit)を使う

Posted at

Nuxt.jsでもAdobe Fontsを使いたい

静的なHTMLページをNuxt.jsで作り直そうと思ったのですが、Adobe Fontsの埋め込みコードを発行しても、以下のようにピュアなJS用のコードしか発行されない。

AdobeFontsが生成するJS
(function (d) {
  var config = {
      kitId: '各自異なるID',
      scriptTimeout: 3000,
      async: true,
    },
    h = d.documentElement,
    t = setTimeout(function () {
      h.className = h.className.replace(/\bwf-loading\b/g, '') + ' wf-inactive'
    }, config.scriptTimeout),
    tk = d.createElement('script'),
    f = false,
    s = d.getElementsByTagName('script')[0],
    a
  h.className += ' wf-loading'
  tk.src = 'https://use.typekit.net/' + config.kitId + '.js'
  tk.async = true
  tk.onload = tk.onreadystatechange = function () {
    a = this.readyState
    if (f || (a && a != 'complete' && a != 'loaded')) return
    f = true
    clearTimeout(t)
    try {
      Typekit.load(config)
    } catch (e) {}
  }
  s.parentNode.insertBefore(tk, s)
})(document)

これだとプロジェクトにそのまま読み込めない。

Googleで調べてみる

Cannot find name 'Typekit'

Nuxt.jsでいい感じにAdobe fontsのwebフォントを読み込む

こちらの記事の方法でもできるはできるのですが、Cannot find name 'Typekit'.エラーが出てしまい、buildができない。

Vue.jsでのやり方があった

Vue.jsとBootstrapVue上でAdobeの日本語ウェブフォントを使う

pluginとして、Adobe Fontsで生成されたJSを単体ファイルとして作成し、それを読み込むという方法。これならいけそう!

解決

まずはAdobe Fontsで生成されたJSをpluginsで作成

plugins/typekit.js
/* eslint-disable */
// めちゃめちゃ怒られるのでESLintは切っておく
;(function (d) {
  var config = {
      kitId: '各自異なるID',
      scriptTimeout: 3000,
      async: true,
    },
    h = d.documentElement,
    t = setTimeout(function () {
      h.className = h.className.replace(/\bwf-loading\b/g, '') + ' wf-inactive'
    }, config.scriptTimeout),
    tk = d.createElement('script'),
    f = false,
    s = d.getElementsByTagName('script')[0],
    a
  h.className += ' wf-loading'
  tk.src = 'https://use.typekit.net/' + config.kitId + '.js'
  tk.async = true
  tk.onload = tk.onreadystatechange = function () {
    a = this.readyState
    if (f || (a && a != 'complete' && a != 'loaded')) return
    f = true
    clearTimeout(t)
    try {
      Typekit.load(config)
    } catch (e) {}
  }
  s.parentNode.insertBefore(tk, s)
})(document)

作成したtypekit.jsをグローバルに読み込む

nuxt.config.js
export default {
  ~ 省略 ~
  plugins: [
    { src: '~/plugins/typekit.js', mode: 'client' }
  ],
  ~ 省略 ~
}

ここでmode: 'client'オプションをつけておかないと、SSR時に「documentが見つからないよ!」となるので注意。

おしまい

有料だし、あんまりAdobe Fontsを使うことはないかもしれないけどAdobe CC契約している人はぜひ。

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2