Skip to content

ProvidePlugin doesn't work on modules that have "polyfill guards" #5828

@fstanis

Description

@fstanis

Do you want to request a feature or report a bug?
bug

What is the current behavior?
If a module polyfills an API, e.g. fetch, the module code might check if window.fetch is already defined:

if (typeof fetch === 'undefined') {
  module.exports = // fetch polyfill
} else {
  module.exports = fetch;
}

This module can then be included by using e.g. const fetch = require('fetch-polyfill'); or, ideally, via ProvidePlugin:

module.exports = {
  ...
  plugins: [
    ...
    new webpack.ProvidePlugin({
      fetch: 'fetch-polyfill'
    })
  ]
}

However, this doesn't work - since fetch is used in the module itself (if (typeof fetch...), this "confuses" webpack and fetch becomes an empty object ({}). Importing the module as anything other than "fetch" works fine, e.g.

module.exports = {
  ...
  plugins: [
    ...
    new webpack.ProvidePlugin({
      myfetch: 'fetch-polyfill'
    })
  ]
}

...but this defeats the purpose of a polyfill.

webextension-polyfill relies on this "polyfill guard", which if how I found out about the issue.

If the current behavior is a bug, please provide the steps to reproduce.
https://gist.github.com/fstanis/450776f48682e6ff85b7c7ba366a5d1e

What is the expected behavior?
ProvidePlugin matching the behaviour of const <name> = require('<module>');

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions