Search code examples
reactjsviteoctokitoctokit-js

Octokit.js not working with Vite. Module externalized and cannot be accessed in client mode


What am I doing?

I am using Vite for my React app. I'm importing Octokit and binding it like this:

import { Octokit } from "octokit";
const githubToken = import.meta.env.REACT_APP_GITHUB_TOKEN;
const octokit = new Octokit({auth: githubToken});

I expect this to function normally. As in, I expect to make requests using octokit perfectly fine.

What am I experiencing?

Or at least, it starts with this: Module "stream" has been externalized for browser compatibility and cannot be accessed in client code.


Solution

  • I'm not sure if this is a credible solution, it worked for me, but it feels more like a work-around. Also, I wasn't inclined on putting enough effort to create a "minimal reproduction repo" so I wasn't able to post this as an issue on Vite's repo.

    Anyway, I solved Module "stream" has been externalized for browser compatibility and cannot be accessed in client code. by:

    1. Installing isomorphic-fetch by yarn add isomorphic-fetch.
    2. Changing my vite.config.js to alias isomorphic-fetch for node-fetch.

    Modified vite.config.js:

    export default defineConfig({
      plugins: [react()],
      resolve: {
        alias: {
          'node-fetch': 'isomorphic-fetch',
        },
      },
    })
    

    This, however, led to an issue of Module "os" has been externalized for browser compatibility and cannot be accessed in client code.

    I fixed that by changing import { Octokit } from "octokit"; to import { Octokit } from "@octokit/core";.

    This led me to the next issue, global not defined.

    Had to "fix" that by adding

     define: {
        "global": {},
      },
    

    to vite.config.js.

    If you have a better solution, let me know.