Build problem with React viteJS and was amplify

Viewed 2870

my question is quite simple to explain. I've initialized a React project with ViteJS and then added aws-amplify for the backend. I developed the project and everything works in my local environment running npm run dev. The problem is that I cannot build it. You can see the error in the text below. Do you have any idea?

'request' is not exported by __vite-browser-external, imported by node_modules/@aws-sdk/credential-provider-imds/dist/es/remoteProvider/httpRequest.js

Error logs

5 Answers

In vite.config.js add:

resolve: {
    alias: {
      './runtimeConfig': './runtimeConfig.browser',
    },
}

in define field

Working config for React polyfilled for AWS SDK and Amplify

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import rollupNodePolyFill from "rollup-plugin-node-polyfills";
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  optimizeDeps: {
    esbuildOptions: {
      // Node.js global to browser globalThis
      define: {
        global: "globalThis", //<-- AWS SDK 
      },
    },
  },
  build: {
    rollupOptions: {
      plugins: [
        // Enable rollup polyfills plugin
        // used during production bundling
        rollupNodePolyFill(),
      ],
    },
  },
  resolve: {
    alias: {
      './runtimeConfig': './runtimeConfig.browser', // <-- Fix from above
    },
  }
});

when using an array of aliases.


  resolve: {
    alias: [
      {
        find: '@', replacement: path.resolve(__dirname, './src'),
      },
      {
        find: './runtimeConfig', replacement: './runtimeConfig.browser',
      }

    ]
  }

For the issue "'request' is not exported by __vite-browser-external", just install the http package (e.g 'npm i http')

It appears root cause of this type of issue is that aws-amplify JS lib is relying on Node specific features. There is a two part workaround:

  1. To solve errors like 'xxxxx' is not exported by __vite-browser-external add additional alias for ./runtimeConfig to the vite.config.ts file. So it will look something like:
alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
      './runtimeConfig': './runtimeConfig.browser',
    },
  1. To solve error like Uncaught ReferenceError: global is not defined, declare corresponding global variable in your topmost html file (index.html)
<script>
    var global = global || window;
    var Buffer = Buffer || [];
    var process = process || {
      env: { DEBUG: undefined },
      version: []
    };
</script>

There is github issue open for more than a year now: https://github.com/aws-amplify/amplify-js/issues/9639

Related