React-static: Error when loading fonts with webfontloader

Created on 1 Nov 2017  路  4Comments  路  Source: react-static/react-static

Hello,

I am trying to use webfontloader to load async my google fonts.

I am using it in this manner in my index.js:

var WebFont = require('webfontloader');

  WebFont.load({
    google: {
      families: ['Droid Sans', 'Droid Serif']
    }
  });

Building it locally is fine, but when building on production I get this error:
ReferenceError: window is not defined

I tried to combine it with jsdom following this example:
https://stackoverflow.com/questions/34425562/getting-webfontloader-to-work-with-node-js-and-jsdom

and I get a couple of errors on build time:

Module not found: Can't resolve 'child_process' in ...
Module not found: Can't resolve 'fs' in...
...

I guess I need a special webpack loader for jsdom?

Is there another way to load google fonts anyc without webfontloader and jsdom?

Any help would be appreciated, thanks a lot!

Most helpful comment

Then just wrap the require within the if-block too and you're good to go 馃槂
Basically you have just to ensure that no code that can only executed on the browser is executed inside a node.js environment, which it is without the if to build the static pages.

With the example of @EmilTholin:

// This will make sure WebFont.load is only used in the browser.
if (typeof window !== 'undefined') {
    var WebFont = require('webfontloader');

    WebFont.load({
        google: {
            families: ['Droid Sans', 'Droid Serif'],
        },
    });
}

All 4 comments

I have never used WebFont, but shouldn't you just use it in the browser at runtime, not in the build step?

You could try this:

var WebFont = require('webfontloader');

// This will make sure WebFont.load is only used in the browser.
if (typeof window !== "undefined") {
  WebFont.load({
    google: {
      families: ['Droid Sans', 'Droid Serif']
    }
  });
}

The problem is here:
var WebFont = require('webfontloader');

require executes webfontloader script which uses window

Then just wrap the require within the if-block too and you're good to go 馃槂
Basically you have just to ensure that no code that can only executed on the browser is executed inside a node.js environment, which it is without the if to build the static pages.

With the example of @EmilTholin:

// This will make sure WebFont.load is only used in the browser.
if (typeof window !== 'undefined') {
    var WebFont = require('webfontloader');

    WebFont.load({
        google: {
            families: ['Droid Sans', 'Droid Serif'],
        },
    });
}

It worked, thanks a lot @calvinrbnspiess !

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tomagladiator picture tomagladiator  路  3Comments

getDanArias picture getDanArias  路  4Comments

tannerlinsley picture tannerlinsley  路  3Comments

stefan-h-singer picture stefan-h-singer  路  3Comments

pbgms picture pbgms  路  3Comments