gatsbyjs / gatsby

The best React-based framework with performance, scalability and security built in.
https://www.gatsbyjs.com
MIT License
55.21k stars 10.33k forks source link

WebpackError: self is not defined #8612

Closed PierreBresson closed 5 years ago

PierreBresson commented 5 years ago

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 commented 5 years ago

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

stepheljobs commented 5 years ago

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 commented 5 years ago

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

jpmasud commented 5 years ago

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

zyhou commented 5 years ago

Same issue with whatwg-fetch, 2.0.4 → 3.0.0.

jpmasud commented 5 years ago

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 commented 5 years ago

Same issue

muhajirdev commented 5 years ago

@PierreBresson did you find a fix for this?

muhajirdev commented 5 years ago

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 commented 5 years ago

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

AAverin commented 5 years ago

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 commented 5 years ago

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 commented 5 years ago

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

Douglashdaniel commented 5 years ago

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

muhajirdev commented 5 years ago

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

Douglashdaniel commented 5 years ago

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 commented 5 years ago

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 commented 5 years ago

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 commented 5 years ago

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

kyleshevlin commented 5 years ago

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 commented 5 years ago

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

kyleshevlin commented 5 years ago

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 commented 5 years ago

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: https://github.com/gatsbyjs/gatsby/issues/3006#issuecomment-459540756.

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

nevace commented 5 years ago

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

adelin-b commented 5 years ago

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 commented 5 years ago

@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 commented 5 years ago

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 commented 5 years ago

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 commented 5 years ago

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 commented 5 years ago

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

Ehesp commented 4 years ago

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 commented 4 years ago

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

hsetially commented 4 years ago

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 commented 4 years ago

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