Polyfills fails in WebWorker environment due to missing window object
Created by: whymatter
Describe the bug
Using the ie9 polyfill throws an error when using it inside a WebWorker since the windows object does not exist. Usually, the polyfills do check whether the window object exists or not. Same applies for the ie11 polyfills. (Using IE11 for testing)
Requires window object:
ie9.js:
require('raf').polyfill(window);
ie11.js:
window.Promise = require('promise/lib/es6-extensions.js');
Does not polyfill fetch if window object is undefined:
ie11.js:
if (typeof window !== 'undefined') {
// fetch() polyfill for making API calls.
require('whatwg-fetch');
}
Did you try recovering your dependencies?
yes, npm Version: 6.4.1
Which terms did you search for in User Guide?
not relevant
Environment
Environment Info:
System:
OS: Windows 10
CPU: (4) x64 Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz
Binaries:
Node: 10.15.3 - C:\Program Files\nodejs\node.EXE
Yarn: 1.16.0 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
npm: 6.4.1 - C:\Program Files\nodejs\npm.CMD
Browsers:
Edge: 44.18956.1000.0
Internet Explorer: 11.0.18956.1000
npmPackages:
react: ^16.9.0 => 16.9.0
react-dom: ^16.9.0 => 16.9.0
react-scripts: 3.1.0 => 3.1.0
npmGlobalPackages:
create-react-app: Not Found
Steps to reproduce
Use the ie9 polyfill inside a WebWorker, loaded by worker-loader (https://github.com/webpack-contrib/worker-loader)
Expected behavior
Polyfill import should not throw an exception because of the missing window object.
Actual behavior
Since the windows object does not exist inside a WebWorker, the last line of the ie9 polyfill throws.
Reproducible demo
Create a new react app, use worker-loader inside you webpack.config.js and load the ie9 polyfill inside the WebWorker.
Example:
test.worker.js
import 'react-app-polyfill/ie9';
index.js
import Worker from './test.worker.js';
const worker = Worker();
webpack.config.js
// ....
module: {
// ...
rules: [
// ....
{
test: /\.worker\.js$/,
use: {
loader: 'worker-loader',
options: { fallback: true }
}
}
]
}
Proposal
Check if the window object is defined:
if (typeof window !== 'undefined') {
require('raf').polyfill(window);
}
if (typeof window !== 'undefined' || typeof self !== 'undefined') {
// fetch() polyfill for making API calls.
require('whatwg-fetch');
}
if (typeof window !== 'undefined') {
window.Promise = require('promise/lib/es6-extensions.js');
} else if (typeof self !== 'undefined') {
self.Promise = require('promise/lib/es6-extensions.js');
}