Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WebpackError: self is not defined #8612

Closed
PierreBresson opened this issue Sep 28, 2018 · 34 comments
Closed

WebpackError: self is not defined #8612

PierreBresson opened this issue Sep 28, 2018 · 34 comments

Comments

@PierreBresson
Copy link

Description

Suddently I cannot build anymore while develop is working well. I have the following error :

error Building static HTML for pages failed

See our docs page on debugging HTML builds for help https://goo.gl/yL9lND

   6 |
   7 |   var support = {
>  8 |     searchParams: 'URLSearchParams' in self,
     | ^
   9 |     iterable: 'Symbol' in self && 'iterator' in Symbol,
  10 |     blob:
  11 |       'FileReader' in self &&


  WebpackError: self is not defined

  - fetch.umd.js:8
    ~/whatwg-fetch/dist/fetch.umd.js:8:1

  - fetch.umd.js:2 support.searchParams
    ~/whatwg-fetch/dist/fetch.umd.js:2:1

  - fetch.umd.js:5 Object.defineProperty.value
    ~/whatwg-fetch/dist/fetch.umd.js:5:2

  - index.cjs.js:3 Object.<anonymous>
    ~/@firebase/polyfill/dist/index.cjs.js:3:1

  - index.cjs.js:5 Object.<anonymous>
    ~/firebase/app/dist/index.cjs.js:5:1

  - firebase.js:1 Object.<anonymous>
    src/firebase/firebase.js:1:1

Steps to reproduce

Just run gatsby build

Expected result

Get files in public folder.

Actual result

Crash on build. The real fun is that gatsby build used to work and I did tag a specific commit to make sure I can go back to this "working version". I revert to this commit and surprise, it's not working anymore.

Environment

gatsby info --clipboard

  System:
    OS: macOS High Sierra 10.13.6
    CPU: x64 Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
    Shell: 3.2.57 - /bin/bash
  Binaries:
    Node: 8.12.0 - /usr/local/bin/node
    Yarn: 1.7.0 - /usr/local/bin/yarn
    npm: 6.4.1 - /usr/local/bin/npm
  Browsers:
    Chrome: 69.0.3497.100
    Firefox: 61.0.1
    Safari: 12.0
  npmPackages:
    gatsby: 1.9.266 => 1.9.266
    gatsby-link: 1.6.44 => 1.6.44
    gatsby-plugin-react-helmet: 2.0.11 => 2.0.11
    gatsby-plugin-react-next: 1.0.11 => 1.0.11
    gatsby-plugin-sass: 1.0.26 => 1.0.26
    gatsby-plugin-typography: 1.7.19 => 1.7.19
  npmGlobalPackages:
    gatsby-cli: 2.4.2

package.json

    "axios": "0.18.0",
    "bootstrap": "4.1.1",
    "firebase": "5.0.4",
    "gatsby": "1.9.266",
    "gatsby-link": "1.6.44",
    "gatsby-plugin-react-helmet": "2.0.11",
    "gatsby-plugin-react-next": "1.0.11",
    "gatsby-plugin-sass": "1.0.26",
    "gatsby-plugin-typography": "1.7.19",
    "react-helmet": "5.2.0",
    "serve": "^10.0.2",
    "typography-theme-ocean-beach": "0.15.11"
@kakadiadarpan
Copy link
Contributor

@PierreBresson can you provide a reproduction repo for this? That would make it much simpler to diagnose this issue.

@kakadiadarpan kakadiadarpan added the status: needs more info Needs triaging and reproducible examples or more information to be resolved label Sep 28, 2018
@stepheljobs
Copy link

stepheljobs commented Oct 1, 2018

I have the similar issue, was debugging all night and I found out it is coming from importing the firebase module.

Just put this anywhere that code will be read...
import firebase from "firebase" this can replicate the issue.

@JordanDDisch
Copy link

Got this error too after updating from Gatsby 2.0.0-beta.111 to 2.0.0-rc.28

@jpmasud
Copy link

jpmasud commented Oct 6, 2018

Same issue here (happens when I try to import firebase)

@zyhou
Copy link

zyhou commented Oct 10, 2018

Same issue with whatwg-fetch, 2.0.4 → 3.0.0.

@jpmasud
Copy link

jpmasud commented Oct 11, 2018

Hi there, turns out you can use a null loader to allow it to build properly. Worked for me with firebase, at least:

In gatsby-node:

exports.onCreateWebpackConfig = ({actions, stage}) => {
    if (stage === "build-html") {
        actions.setWebpackConfig({
            module: {
                rules: [
                    {
                        test: /firebase/,
                        use: ['null-loader']
                    },
                ],
            }
        })
    }
};

@muhajirdev
Copy link
Contributor

Same issue

@muhajirdev
Copy link
Contributor

@PierreBresson did you find a fix for this?

@muhajirdev
Copy link
Contributor

muhajirdev commented Oct 17, 2018

Hey, guys. If you still facing this issue. I already created a Gatsby + Firebase starter that works. Tried with latest gatsby and latest firebase. https://github.com/muhajirframe/gatsby-starter-firebase

@AAverin
Copy link

AAverin commented Oct 30, 2018

I have this error with Gatsby 1 and Firebase 4, which are supposed to work together nicely

@AAverin
Copy link

AAverin commented Oct 31, 2018

Same with following set of dependencies:

"dependencies": {
    "@material-ui/core": "^3.2.2",
    "@material-ui/icons": "^3.0.1",
    "aws-sdk": "^2.345.0",
    "cookieconsent": "^3.0.6",
    "firebase": "^5.5.5",
    "firebaseui": "^3.4.1",
    "fsevents": "^1.2.4",
    "gatsby": "^1.9.247",
    "gatsby-link": "^1.6.36",
    "gatsby-plugin-google-analytics": "^1.0.17",
    "gatsby-plugin-i18n": "^0.4.1",
    "gatsby-plugin-react-helmet": "^1.0.8",
    "gatsby-plugin-react-next": "^1.0.11",
    "material-ui-chip-input": "^1.0.0-beta.8",
    "paypal-checkout": "^4.0.228",
    "react": "^16.5.2",
    "react-dom": "^16.5.2",
    "react-firebaseui": "^3.1.2",
    "react-intl": "^2.4.0",
    "reactstrap": "^5.0.0-beta"
  },

@AAverin
Copy link

AAverin commented Nov 3, 2018

Looks like Firebase is using a polyfill for fetch that references window.self

Would it be safe to apply null-loader for firebase and wrap all it's calls into:

if (typeof window !== 'undefined') {
  firebase.initializeApp(config);
}

??

@AAverin
Copy link

AAverin commented Nov 3, 2018

Removing firebase with a null-loader introduced lots of other issues in the project
Any other known workarounds?

@Douglashdaniel
Copy link

I'm having the same issue :/

error Building static HTML for pages failed

See our docs page on debugging HTML builds for help https://goo.gl/yL9lND

1 | var support = {

2 | searchParams: 'URLSearchParams' in self,
| ^
3 | iterable: 'Symbol' in self && 'iterator' in Symbol,
4 | blob:
5 | 'FileReader' in self &&

WebpackError: ReferenceError: self is not defined

  • fetch.js:2 Module../node_modules/whatwg-fetch/fetch.js
    [lib]/[whatwg-fetch]/fetch.js:2:1

  • bootstrap:19 webpack_require
    lib/webpack/bootstrap:19:1

  • index.esm.js:1 Module../node_modules/@firebase/polyfill/dist/index.esm.js
    [lib]/[@firebase]/polyfill/dist/index.esm.js:1:1

  • bootstrap:19 webpack_require
    lib/webpack/bootstrap:19:1

  • index.esm.js:1 Module../node_modules/firebase/dist/index.esm.js
    [lib]/[firebase]/dist/index.esm.js:1:1

  • bootstrap:19 webpack_require
    lib/webpack/bootstrap:19:1

  • fire.js:1 Module../src/components/fire/fire.js
    lib/src/components/fire/fire.js:1:1

  • bootstrap:19 webpack_require
    lib/webpack/bootstrap:19:1

  • header.js:1 Module../src/components/header.js
    lib/src/components/header.js:1:1

  • bootstrap:19 webpack_require
    lib/webpack/bootstrap:19:1

  • bootstrap:19 webpack_require
    lib/webpack/bootstrap:19:1

  • 404.js:1 Module../src/pages/404.js
    lib/src/pages/404.js:1:1

  • bootstrap:19 webpack_require
    lib/webpack/bootstrap:19:1

  • sync-requires.js:6 Object../.cache/sync-requires.js
    lib/.cache/sync-requires.js:6:49

  • bootstrap:19 webpack_require
    lib/webpack/bootstrap:19:1

@muhajirdev
Copy link
Contributor

muhajirdev commented Nov 19, 2018

The implementation on starter above should fix the issue . Feel free to reopen again in case you still have an issue

@Douglashdaniel
Copy link

Can you not just tell us what you did to fix the issue? I'd rather not fork my project over to yours! that would take days.

@muhajirdev
Copy link
Contributor

Sure,
use gatsby-plugin-layout. And the key implementation is in https://github.com/muhajirframe/gatsby-starter-firebase/blob/master/src/layouts/index.js .

Basicly it load firebase on componentDidMount(). And put firebase in react context that's it.

@Douglashdaniel
Copy link

Awesome! Thank you! I have also found another solve for this issue,

  1. Delete node_modules
  2. run npm i whatwg-fetch@2.0.4 --save
  3. run npm install

@lexicalparadoxx
Copy link

@Douglashdaniel this used to work for me, but not it just started to run into the same error as above

@kyleshevlin
Copy link

kyleshevlin commented Jan 26, 2019

I feel like the solution proposed is misleading (at least without further explanation), for the following reasons:

  1. What does gatsby-plugin-layout have to do with anything regarding firebase?
  2. Why does it have to be put into context?
  3. Why do we have to dynamically import firebase? That's the question that needs to be most answered here. Dynamic imports solve the problem, but does not explain what the original problem is.

@mufaddalmw
Copy link

@jpmasud after adding code you mentioned it throws another error -
WebpackError: TypeError: htmlComponentRenderer.default is not a function

@kyleshevlin
Copy link

FWIW to future visitors of this thread, in response to my previous post, gatsby-plugin-layout and putting a firebase instance into context are not necessary steps to solving the issue of loading the Firebase SDK with Gatsby. Dynamic importing is necessary. Here's why.

Firebase has an initializeApp method that makes reference to the window object. Gatsby does not have access to the window object in its build phase. Thus, we need to delay the initialization of Firebase until we have access to that object. Dynamically importing it in a component's componentDidMount lifecycle hook guarantees this. However, this is not the end of solving the problem.

The reason context was used, but isn't the only means of solving this problem, is to create a Firebase singleton in your application, that is, only one instance of initialized Firebase being consumed by your app. If you're going to dynamically import and then initialize Firebase in the client, you will have to come up with a strategy to guarantee you only initialize one instance and use it through out your app. The example above by @muhajirframe does show an example with the getFirebase function.

Best of luck getting this working. I wrote about it in a blog post should you want more details of how I solved this problem: https://kyleshevlin.com/firebase-and-gatsby-together-at-last.

@fivetwelve
Copy link

fivetwelve commented Jan 31, 2019

I came to this thread due to whatwg-fetch causing me similar issues (however I am not using Firebase). With one version, it would work in build but not develop. Downgrading from 3.0.0 to 2.0.4 caused the opposite, failing build and working in develop. Details in my comment in a similar issue: #3006 (comment).

Summary: I switched to fetch-ponyfill and it worked in both scenarios.

@nevace
Copy link

nevace commented Mar 8, 2019

importing it into the gatsby-browser.js file fixed it for me.

@adelin-b
Copy link

importing it into the gatsby-browser.js file fixed it for me.

what do you meant by "it" ? just tryed a few packages quoted here but didnt worked well.

@nevace
Copy link

nevace commented Jun 25, 2019

@adberard the issue was caused by 'window' not being defined in a gatsby build. I had imported 'whatwg-fetch' in a javascript file like normal but it needs adding to the gatsby-browser.js file here.

import 'whatwg-fetch'

I'm assuming firebase has the same issue where it's using fetch internally and using the library in a gatsby project is causing the same issue.

@EdgarNigel
Copy link

Thanks @nevace, this helped. It is important to remove the 'whatwg-fetch' import in any other js file and solely import it in gatsby-browser.js

@jeremyswann
Copy link
Contributor

This turned out to be a window undefined bug for me, I am using MongoDB Stitch which uses 'whatwg-fetch' as a dependancy. A simple truthy statement fixed it.

const isWindow = typeof window !== 'undefined' && window
componentDidMount() {
	if (isWindow) {
		const { Stitch } = require('mongodb-stitch-browser-sdk')
		this.client = Stitch.initializeDefaultAppClient('xxxx')
	}
}

@AAverin
Copy link

AAverin commented Sep 16, 2019

While the solution to import firebase in componentDidMount solved most of the problems, there is one case when it doesn't work - referencing firebase.auth.EmailAuthProvider.PROVIDER_ID.
Here firebase needs to be imported, but importing it wrongly references browser-version of firebase, so gatsby fails to build.
Any other possible workarounds?

@AAverin
Copy link

AAverin commented Sep 16, 2019

I tried and looks like this also works fine for providers.
Lazy firebase initialization is the only solution, it seems.

@Ehesp
Copy link
Contributor

Ehesp commented Oct 9, 2019

Sorted the issue for me. In my onClick handler I now have this:

      const instance = require('firebase');
      const provider = new instance.auth.GithubAuthProvider();
      await firebase.auth().signInWithRedirect(provider);

The firebase variable is my initialised one.

@codercatdev
Copy link

Tried the webpack solution which got past the performance Index issue, but now it fails on the Google Auth proviers.

gatsby-node.js

exports.onCreateWebpackConfig = ({ getConfig, stage, actions }) => {
  const config = getConfig()
  if (stage.startsWith('develop') && config.resolve) {
    config.resolve.alias = {
      ...config.resolve.alias,
      'react-dom': '@hot-loader/react-dom'
    }
  }
  if (stage === "build-html") {
    actions.setWebpackConfig({
        module: {
            rules: [
                {
                    test: /firebase/,
                    use: ['null-loader']
                },
            ],
        }
    })
  }
}

image

dwltkvn added a commit to dwltkvn/arena-match-maker that referenced this issue Nov 5, 2019
@hsetially
Copy link

In my case i was trying to connect to Stitch using mongodb-stitch-browser-sdk in a gatsby application and building of static html pages failed.
Solved using react-loadable ( Imported the component where the Stitch is called using react-loadable)

@djodjo02130
Copy link

@hsetially Can you show how did you use react-loadable and mongodb-stitch-browser-sdk ? Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests