pexels / pexels-javascript

Official Javascript library for the Pexels API.
https://www.pexels.com/api/documentation/
145 stars 29 forks source link

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

Open donizer opened 1 year ago

donizer commented 1 year ago

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 commented 1 year ago

Have the exact same isssue here

samuelkarani commented 1 year ago

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 commented 11 months ago

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 commented 10 months ago

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

arwin4 commented 10 months ago

@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 commented 3 months ago

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 commented 1 month ago

having the same issue in Nuxt3

mrmind3312 commented 1 week ago

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);
});