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

Uncaught ReferenceError with require("isomorphic-fetch") #49

Open
donizer opened this issue Jun 27, 2023 · 9 comments
Open

Uncaught ReferenceError with require("isomorphic-fetch") #49

donizer opened this issue Jun 27, 2023 · 9 comments

Comments

@donizer
Copy link

donizer commented Jun 27, 2023

I am using the Pexels library with React and TypeScript, built on Vite, for my pet project.

While I start the app on the development server npm run dev, everything works as expected. However, when I try to run the build version using npm run build and npm run preview, I encounter an error: Uncaught ReferenceError: require is not defined at index-e209a5d9.js:10314:1

The error is caused by the line require("isomorphic-fetch"); in the file ../dist/assets/index-e209a5d9.js

I searched all my modules and only Pexels have dependency on 'isomorphic-fetch'.

...
function Ph(e) {
  if (!e || typeof e !== "string")
    throw new TypeError(
      "An API key must be provided when initiating the Pexels client."
    );
  return { typeCheckers: _h, photos: xh(e), videos: Ch(e), collections: Eh(e) };
}
require("isomorphic-fetch"); // here
const Nh = Ph("qaxLvqCpYIxuOSlbBG6BYEoZup3UZpB8a7PZ2JGEiWO7CPzmmQbQDGp7"),
  Lh = async (e) => ({
    values: e.query ? e : {},
    errors: e.query
      ? {}
      : { query: { type: "required", message: "Input required" } },
  });
...

Based on how it looks, it seems that the require("isomorphic-fetch"); line does nothing, so I tried deleting it. After removing this line, the program started working and fetch data.

However, I don't know what should i do next to prevent this error for next builds.

@samuelkarani
Copy link

Have the exact same isssue here

@samuelkarani
Copy link

Apparently its a issue with vite build in production. I've used this quick fix for now in main.tsx:
declare global { interface Window { require: any; } } window.require = (name: string) => new URL(name, import.meta.url).href;

@arwin4
Copy link

arwin4 commented Oct 1, 2023

I'm facing the same issue, but I'm not using TypeScript (and I'm unfamiliar with it). Would such a workaround be possible in jsx?

edit: Ended up dropping the wrapper altogether. fetch() works just fine.

@catiaraquelabreu
Copy link

@arwin4 Did you fix it? Im having the same issue

@arwin4
Copy link

arwin4 commented Nov 3, 2023

@catiaraquelabreu

I wasn't able to fix this error. For my project, I just needed one simple API call, so I ended up using the native fetch(). This is my implementation, hope it helps.

  const imageRequest = await fetch(
    `https://api.pexels.com/v1/search?query=${query}&per_page=15&page=1`,
    {
      headers: {
        Authorization: APIkey,
      },
    },
  ).then((response) => response.json());

@bshortdev
Copy link

My guess is that one of the dependencies uses commonJS. Another issue had the fix that worked for me, which was adding this to my vite.config.js file

build: {
    commonjsOptions: {
      transformMixedEsModules: true,
    },
  },

@mics-devs-stuff
Copy link

having the same issue in Nuxt3

@mrmind3312
Copy link

having the same issue in Nuxt3

Same issue suggestions drop off the client and make your own wrapper like this:

export default defineNuxtPlugin(nuxtApp => {
  const config = useRuntimeConfig();
  const API_KEY = config.app.pexelsApiKey;

  // Create a function to make requests to the Pexels API
  const pexelsApiWrapper = {
    async searchPhotos(query, options = {}) {
      const { per_page = 10, page = 1 } = options;
      const response = await fetch(`https://api.pexels.com/v1/search?query=${encodeURIComponent(query)}&per_page=${per_page}&page=${page}`, {
        headers: {
          Authorization: API_KEY
        }
      });

      if (!response.ok) {
        throw new Error(`Error fetching data from Pexels: ${response.statusText}`);
      }

      const data = await response.json();
      return data;
    },

    async getPhoto(id) {
      const response = await fetch(`https://api.pexels.com/v1/photos/${id}`, {
        headers: {
          Authorization: API_KEY
        }
      });

      if (!response.ok) {
        throw new Error(`Error fetching photo from Pexels: ${response.statusText}`);
      }

      const data = await response.json();
      return data;
    },

    // Add other API methods as needed
  };

  // Provide the custom Pexels API wrapper to the Nuxt application
  nuxtApp.provide('pexelsClient', pexelsApiWrapper);
});

@emrslmz
Copy link

emrslmz commented Sep 13, 2024

Adding it solved my problem; thank you very much

build: { commonjsOptions: { transformMixedEsModules: true, }, },

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

8 participants