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!
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 !
Most helpful comment
Then just wrap the
requirewithin 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
browseris executed inside anode.jsenvironment, which it is without the if to build the static pages.With the example of @EmilTholin: