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

Cannot use amplify-js in browser environment (breaking vite / snowpack / esbuild) #9639

Closed
sem4phor opened this issue Jan 5, 2021 · 120 comments
Assignees
Labels
Build Related to build issues dependencies Pull requests that update a dependency file feature-request Request a new feature

Comments

@sem4phor
Copy link

sem4phor commented Jan 5, 2021

Describe the bug

The package aws-amplify is meant to be used in the browser, isnt it? Therefore it should not rely on node builtins, which sadly is the case and prevents the usage of this package in many js build tools like rollup, snowpack or vitejs.

The @AWS-SDK package which is used by aws-amplify relies on various node build in modules like fs, process or http2, ....

I described the issue also here (vitejs/vite#1374) and Evan You the creator of vuejs and vite mentioned that webpack will drop support for node build ins in version five. Because webpack is used by tools such as create-react-app and vue-cli this will block many developers from using the amplify package soon I think!

To Reproduce
Steps to reproduce the behavior:

  1. Download https://github.com/sem4phor/aws-cli-bug
  2. Run npm run dev (node required)
  3. See error in console

Expected behavior
The package works in the browser and does not import any node build ins which are not available in browser environment.

Code Snippet
https://github.com/sem4phor/aws-cli-bug

Screenshots

[plugin:vite:imports] Failed to resolve import "process". Does the file exist?
/Users/XXXXX/node_modules/@aws-sdk/util-user-agent-node/dist/es/index.js:1:22
1  |  import process from "process";
   |                       ^
2  |  export function defaultUserAgent(packageName, packageVersion) {
3  |      var engine = process.platform + "/" + process.version;
Error: Failed to resolve import "process". Does the file exist?
    at TransformContext.error (C:\Users\XXXXX\node_modules\vite\dist\node\chunks\dep-262f13eb.js:59552:50)
    at TransformContext.transform (C:\XXXXX\node_modules\vite\dist\node\chunks\dep-262f13eb.js:52957:30)
    at async Object.transform (C:\Users\XXXXX\node_modules\vite\dist\node\chunks\dep-262f13eb.js:59742:30)
    at async transformRequest (C:\Users\XXXXX\node_modules\vite\dist\node\chunks\dep-262f13eb.js:65977:29)
    at async C:\Users\XXXXX\node_modules\vite\dist\node\chunks\dep-262f13eb.js:66068:32

What is Configured?
Not relevant for this error.

  • OS: Windows 10
  • Browser: Chrome 87
  • aws-amplify 3.3.13
@Jexordexan
Copy link

I'm experiencing the same issue, I have had no luck finding a workaround. I am also using vite. Also @sem4phor, in the issue body, you mention @aws-cli but I believe the problem is with @aws-sdk.

@soerenmartius
Copy link

I second that. The problem seems to be in @aws-sdkSeems like the library has dependencies on node built-in types which is really bad. Seems like the library was built for webpack and is not usable with vite or rollup at the moment? Also, the coupling increases the size of the package significantly.

Are there any plans to get rid of the node dependencies anytime soon?

@ebisbe
Copy link

ebisbe commented Feb 7, 2021

I have the same issue

@Mootook
Copy link

Mootook commented Feb 8, 2021

I was also getting this issue when trying to migrate an existing project onto Vite.

Apparently work is being done on the aws-sdk to update this:
vitejs/vite#1502 (comment)

But I had to follow this to get my app running as Vite is using rollup:
https://dev.to/swyx/making-aws-amplify-work-with-rollup-2d9m

@ebisbe
Copy link

ebisbe commented Feb 9, 2021

But I had to follow this to get my app running as Vite is using rollup:
https://dev.to/swyx/making-aws-amplify-work-with-rollup-2d9m

@Mootook Did that link work for you? I tried and couldn't make it work. I'm new to Rollup / Vite so I wasn't even sure it would work. I'll try again if that worked then.

@mbp
Copy link

mbp commented Feb 9, 2021

But I had to follow this to get my app running as Vite is using rollup:
https://dev.to/swyx/making-aws-amplify-work-with-rollup-2d9m

@Mootook Did that link work for you? I tried and couldn't make it work. I'm new to Rollup / Vite so I wasn't even sure it would work. I'll try again if that worked then.

I have the same issue (and also new to Rollup / Vite), so I am not sure how you would make the changes in e.g. vite.config.ts file where the syntax is different. Let me know if you make it work!

@sem4phor
Copy link
Author

sem4phor commented Feb 9, 2021

@Mootook It would be great if you could provide a repository with your suggested workaround :)

@ebisbe
Copy link

ebisbe commented Feb 9, 2021

From what I have read the plugin interface of Vite is the same as Rollup so they should be compatible. What I don't understand is that in https://vite-rollup-plugins.patak.dev you can see that Json and node-resolve are already covered on Vite.

@Mootook
Copy link

Mootook commented Feb 9, 2021

@ebisbe, I didn't know that, good catch.

I have uploaded a small demo https://github.com/Mootook/aws-vite-demo/tree/main

But you're right, the plugin extension in vite.config.js is not necessary. Commenting it out, removing them as dependencies, and rebuilding seems to have no effect.

The only other issue I ran into was a global is not defined error, which has a solution in the index.html file.

@sammartinez
Copy link
Contributor

@sem4phor Are you using Amplify JavaScript or using AWS SDK? I believe your issue is related to the AWS SDK instead of Amplify JS. Can you confirm?

@ebisbe
Copy link

ebisbe commented Feb 9, 2021

@sammartinez Doesn't Aws-amplify use Aws-sdk? I use Aws-amplify but my errors come from node_modules/@AWS-SDK and I have not installed in the package.json

@ebisbe
Copy link

ebisbe commented Feb 9, 2021

@ebisbe, I didn't know that, good catch.

I have uploaded a small demo https://github.com/Mootook/aws-vite-demo/tree/main

But you're right, the plugin extension in vite.config.js is not necessary. Commenting it out, removing them as dependencies, and rebuilding seems to have no effect.

The only other issue I ran into was a global is not defined error, which has a solution in the index.html file.

Your code is working indeed. But when I add your vite.config.js it still fails in mine... I've been trying to sample the minimum to make it work on my project but it doesn't. Besides what you have I'm using Tailwind

@sammartinez
Copy link
Contributor

@ebisbe correct, we use AWS SDK but it is a dependency and separate team and repo that handles errors related to it.

@Mootook
Copy link

Mootook commented Feb 9, 2021

@ebisbe, I updated my repo to use tailwind and it's working.

What errors are you getting?
Is it still failing on the amplify dependency?

there is also a vite specific discord for general troubleshooting
https://discord.gg/y44Ad4hF

@mbp
Copy link

mbp commented Feb 9, 2021

@Mootook correct me if I am wrong, but I don't actually see you using aws-amplify in your repo (other than the package.json dependency)

If you insert the following code into main.js:

import Amplify, { Auth } from 'aws-amplify';

Amplify.configure({});

Then npm run build will start failing with

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

This is the error message originally reported in the chain of issues: vitejs/vite#1502 => vitejs/vite#1374 (comment) => this

@Mootook
Copy link

Mootook commented Feb 9, 2021

@mbp
Ah! Yes, you're correct. Apologies, I just went off the original steps to reproduce, which just included npm run dev (which does work, even with Amplify.configure()...odd), but the error is present in npm run build.

So credential provider is expecting the node http global which is not bundled with rollup.
There is the 'rollup-plugin-node-builtins' package, but it seems outdated and sort of undercuts what Vite is striving for.

@ebisbe
Copy link

ebisbe commented Feb 10, 2021

@ebisbe, I updated my repo to use tailwind and it's working.

What errors are you getting?
Is it still failing on the amplify dependency?

there is also a vite specific discord for general troubleshooting
https://discord.gg/y44Ad4hF

It's funny because when I moved my code to your repo it's all working but in mine it still failing. I've forked your repo with my code added in https://github.com/ebisbe/aws-vite-demo and my failing code in here https://github.com/ebisbe/skedr-prototype/tree/live

The error I get is:

⌊☻ yarn dev
yarn run v1.22.10
$ vite --open
Pre-bundling dependencies:
  vue
  vue-router
  aws-amplify
  luxon
  lodash/groupBy
  (...and 1 more)
(this will be run only when your dependencies or config have changed)
 > node_modules/@aws-sdk/credential-provider-imds/dist/es/remoteProvider/httpRequest.js: error: No matching export for import "request"
    4 │ import { request } from "http";
      ╵          ~~~~~~~

 > node_modules/@aws-sdk/shared-ini-file-loader/dist/es/index.js: error: No matching export for import "readFile"
    2 │ import { readFile } from "fs";
      ╵          ~~~~~~~~

 > node_modules/@aws-sdk/shared-ini-file-loader/dist/es/index.js: error: No matching export for import "homedir"
    3 │ import { homedir } from "os";
      ╵          ~~~~~~~

 > node_modules/@aws-sdk/shared-ini-file-loader/dist/es/index.js: error: No matching export for import "join"
    4 │ import { join, sep } from "path";
      ╵          ~~~~

 > node_modules/@aws-sdk/shared-ini-file-loader/dist/es/index.js: error: No matching export for import "sep"
    4 │ import { join, sep } from "path";
      ╵                ~~~

 > node_modules/@aws-sdk/credential-provider-process/dist/es/index.js: error: No matching export for import "exec"
    4 │ import { exec } from "child_process";
      ╵          ~~~~

 > node_modules/@aws-sdk/node-http-handler/dist/es/write-request-body.js: error: No matching export for import "Readable"
    1 │ import { Readable } from "stream";
      ╵          ~~~~~~~~

 > node_modules/@aws-sdk/node-http-handler/dist/es/node-http-handler.js: error: No matching export for import "Agent"
    3 │ import { Agent as hAgent, request as hRequest } from "http";
      ╵          ~~~~~

 > node_modules/@aws-sdk/node-http-handler/dist/es/node-http-handler.js: error: No matching export for import "request"
    3 │ import { Agent as hAgent, request as hRequest } from "http";
      ╵                           ~~~~~~~

 > node_modules/@aws-sdk/node-http-handler/dist/es/node-http-handler.js: error: No matching export for import "Agent"
    4 │ import { Agent as hsAgent, request as hsRequest } from "https";
      ╵          ~~~~~

 > node_modules/@aws-sdk/node-http-handler/dist/es/node-http-handler.js: error: No matching export for import "request"
    4 │ import { Agent as hsAgent, request as hsRequest } from "https";
      ╵                            ~~~~~~~

 > node_modules/@aws-sdk/node-http-handler/dist/es/node-http2-handler.js: error: No matching export for import "connect"
    4 │ import { connect, constants } from "http2";
      ╵          ~~~~~~~

 > node_modules/@aws-sdk/node-http-handler/dist/es/node-http2-handler.js: error: No matching export for import "constants"
    4 │ import { connect, constants } from "http2";
      ╵                   ~~~~~~~~~

 > node_modules/@aws-sdk/node-http-handler/dist/es/stream-collector/collector.js: error: No matching export for import "Writable"
    2 │ import { Writable } from "stream";
      ╵          ~~~~~~~~

 > node_modules/@aws-sdk/util-body-length-node/dist/es/index.js: error: No matching export for import "lstatSync"
    1 │ import { lstatSync } from "fs";
      ╵          ~~~~~~~~~

 > node_modules/@aws-sdk/eventstream-serde-node/dist/es/EventStreamMarshaller.js: error: No matching export for import "Readable"
    4 │ import { Readable } from "stream";
      ╵          ~~~~~~~~

 > node_modules/@aws-sdk/hash-stream-node/dist/es/hash-calculator.js: error: No matching export for import "Writable"
    2 │ import { Writable } from "stream";
      ╵          ~~~~~~~~

 > node_modules/@aws-sdk/hash-stream-node/dist/es/index.js: error: No matching export for import "createReadStream"
    1 │ import { createReadStream } from "fs";
      ╵          ~~~~~~~~~~~~~~~~

error when starting dev server:
Error: Build failed with 18 errors:
node_modules/@aws-sdk/credential-provider-imds/dist/es/remoteProvider/httpRequest.js:4:9: error: No matching export for import "request"
node_modules/@aws-sdk/credential-provider-process/dist/es/index.js:4:9: error: No matching export for import "exec"
node_modules/@aws-sdk/eventstream-serde-node/dist/es/EventStreamMarshaller.js:4:9: error: No matching export for import "Readable"
node_modules/@aws-sdk/hash-stream-node/dist/es/hash-calculator.js:2:9: error: No matching export for import "Writable"
node_modules/@aws-sdk/hash-stream-node/dist/es/index.js:1:9: error: No matching export for import "createReadStream"
...
    at failureErrorWithLog (/Volumes/Data/Development/skedr/next_prototype/node_modules/esbuild/lib/main.js:1124:15)
    at buildResponseToResult (/Volumes/Data/Development/skedr/next_prototype/node_modules/esbuild/lib/main.js:879:32)
    at /Volumes/Data/Development/skedr/next_prototype/node_modules/esbuild/lib/main.js:974:20
    at /Volumes/Data/Development/skedr/next_prototype/node_modules/esbuild/lib/main.js:541:9
    at handleIncomingPacket (/Volumes/Data/Development/skedr/next_prototype/node_modules/esbuild/lib/main.js:624:9)
    at Socket.readFromStdout (/Volumes/Data/Development/skedr/next_prototype/node_modules/esbuild/lib/main.js:508:7)
    at Socket.emit (events.js:314:20)
    at addChunk (_stream_readable.js:298:12)
    at readableAddChunk (_stream_readable.js:273:9)
    at Socket.Readable.push (_stream_readable.js:214:10)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

@sem4phor
Copy link
Author

sem4phor commented Feb 10, 2021

Are you using Amplify JavaScript or using AWS SDK? I believe your issue is related to the AWS SDK instead of Amplify JS. Can you confirm?

@sammartinez I am using amplify which has aws-sdk as it's dependency (see reproduction repository)

The vue label is kinda wrong. It is an issue with js bundlers which use native ecmascript modules. Vite is not vue-only.

@sammartinez sammartinez self-assigned this Feb 10, 2021
@sammartinez
Copy link
Contributor

@sem4phor I guess I am a little confused and will need more information from you. What is your use case you are looking to do ? In looking at the code sample provided, thank you by the way it was helpful, I am not seeing a direct dependency of aws-amplify or an aws-exports file for testing the configuration, just an empty object passed. To some of the errors called out in the stack traces above, we have done some clean up on the library recently to remove unused dependencies. Can you look at testing the latest version of aws-amplify with your sample?

@madmod
Copy link

madmod commented Feb 16, 2021

I too am having this issue. I have imported @aws-sdk/client-cognito-identity and @aws-sdk/credential-provider-cognito-identity directly. I am using Vite and not using Amplify fyi. Hopefully that helps you track down the root cause.

@madmod
Copy link

madmod commented Feb 16, 2021

I have determined that the following modules cause build errors related to expecting various node js modules in the browser such as http and fs.

        '@aws-sdk/credential-provider-imds',
        '@aws-sdk/credential-provider-process',
        '@aws-sdk/shared-ini-file-loader',
        '@aws-sdk/eventstream-serde-node',
        '@aws-sdk/hash-node',
        '@aws-sdk/node-http-handler',
        '@aws-sdk/util-body-length-node',
        '@aws-sdk/util-user-agent-node',

@bhvngt
Copy link

bhvngt commented Mar 7, 2021

I am facing the same issue while using vite.

I am getting the previously reported error 'request' is not exported by __vite-browser-external, imported by node_modules\@aws-sdk\credential-provider-imds\dist\es\remoteProvider\httpRequest.js. Is this something that is fixed? I have tried this with the latest version of aws-amplify 3.3.22.

I tried with rollup config as suggested earlier in this thread. I also experimented with rollup-plugin-polyfill-node. Both of them fails to fix the issue.

Here's my vite.config.js

import svelte from "rollup-plugin-svelte-hot";
import autoPreprocess from "svelte-preprocess";
import nodeResolve from "@rollup/plugin-node-resolve";
import json from "@rollup/plugin-json";

export default {
    alias: {
        "@": resolve(__dirname, "src"),
    },
    root: "src",
    plugins: [
        svelte({
            preprocess: autoPreprocess(),
            dev: true,
            hot: true,
        }),
    ],
    build: {
        rollupOptions: {
            plugins: [
                nodeResolve({
                    browser: true,
                    preferBuiltins: false,
                }),
                json(),
            ],
        },
    },
};

Error dump

'request' is not exported by __vite-browser-external, imported by node_modules/.pnpm/@aws-sdk/credential-provider-imds@3.6.1/node_modules/@aws-sdk/credential-provider-imds/dist/es/remoteProvider/httpRequest.js
file: /temp/tst/node_modules/.pnpm/@aws-sdk/credential-provider-imds@3.6.1/node_modules/@aws-sdk/credential-provider-imds/dist/es/remoteProvider/httpRequest.js:4:9
2: import { ProviderError } from "@aws-sdk/property-provider";
3: import { Buffer } from "buffer";
4: import { request } from "http";
            ^
5: /**
6:  * @internal
error during build:
Error: 'request' is not exported by __vite-browser-external, imported by node_modules/.pnpm/@aws-sdk/credential-provider-imds@3.6.1/node_modules/@aws-sdk/credential-provider-imds/dist/es/remoteProvider/httpRequest.js
    at error (/temp/tst/node_modules/.pnpm/rollup@2.40.0/node_modules/rollup/dist/shared/rollup.js:5279:30)
    at Module.error (/temp/tst/node_modules/.pnpm/rollup@2.40.0/node_modules/rollup/dist/shared/rollup.js:9996:16)
    at Module.traceVariable (/temp/tst/node_modules/.pnpm/rollup@2.40.0/node_modules/rollup/dist/shared/rollup.js:10389:29)
    at ModuleScope.findVariable (/temp/tst/node_modules/.pnpm/rollup@2.40.0/node_modules/rollup/dist/shared/rollup.js:8847:39)
    at FunctionScope.findVariable (/temp/tst/node_modules/.pnpm/rollup@2.40.0/node_modules/rollup/dist/shared/rollup.js:2641:38)
    at ChildScope.findVariable (/temp/tst/node_modules/.pnpm/rollup@2.40.0/node_modules/rollup/dist/shared/rollup.js:2641:38)
    at FunctionScope.findVariable (/temp/tst/node_modules/.pnpm/rollup@2.40.0/node_modules/rollup/dist/shared/rollup.js:2641:38)
    at ChildScope.findVariable (/temp/tst/node_modules/.pnpm/rollup@2.40.0/node_modules/rollup/dist/shared/rollup.js:2641:38)
    at Identifier.bind (/temp/tst/node_modules/.pnpm/rollup@2.40.0/node_modules/rollup/dist/shared/rollup.js:4017:40)
    at CallExpression.bind (/temp/tst/node_modules/.pnpm/rollup@2.40.0/node_modules/rollup/dist/shared/rollup.js:2728:23)

@jarrodu
Copy link

jarrodu commented Mar 16, 2021

I am so glad I found this issue since I was about to write my own.

I am also having this issue.

@sem4phor sem4phor changed the title Cannot use amplify-js in browser environment Cannot use amplify-js in browser environment (breaking vite / snowpack / esbuild) Mar 17, 2021
@vovapyc
Copy link

vovapyc commented Mar 18, 2021

Hi @bhavinkamani-gt, have you manage to fix it?

@jarrodu
Copy link

jarrodu commented Mar 18, 2021

I noticed that the "to-be-reproduced" tag was added to this issue. I am willing to spend a bit of time setting up a minimal example of the issue I am having. Is there a protocol for submitting an example or is a temporary public git repo with a README enough?

@bhvngt
Copy link

bhvngt commented Mar 18, 2021

@vovawed No, I haven't yet found the solution.. As a workaround, I am using snowpack to do my production builds. Snowpack has a built-in support for node-polyfills with snowpack build --polyfill-node.

As commented here. This should have been fixed in this library by isolating node related code. However, it doesn't seem to have happen.

@sammartinez Would you have any update on this issue?

@sem4phor
Copy link
Author

I think to be reprouced relates to a maintainer who needs to reproduce this. I have already submitted a reproduction repository...

Moreover the label Amplify UI Components is wrong, too IMO. The issue persists without importing ui components @sammartinez

@samputer
Copy link

samputer commented Feb 15, 2023

I had to update my Vite config to the following to get both build time & dev working (only the relevant parts of the config are included):

export default defineConfig({
  ...(process.env.NODE_ENV === 'development'
    ? {
      define: {
        global: {},
      },
    }
    : {}),
  resolve: {
    alias: {
      ...(process.env.NODE_ENV !== 'development'
        ? {
          './runtimeConfig': './runtimeConfig.browser', //fix production build
        }
        : {}),
    },
  },
});

I got both dev and prod builds working with @ffxsam 's solution - thanks!

My whole vite.config.ts (with Vuetify):

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath } from 'url'
import vuetify from 'vite-plugin-vuetify'

// https://vitejs.dev/config/
export default defineConfig({
  ...(process.env.NODE_ENV === 'development'
    ? {
      define: {
        global: {},
      },
    }
    : {}),
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
      ...(process.env.NODE_ENV !== 'development'
        ? {
          './runtimeConfig': './runtimeConfig.browser', //fix production build
        }
        : {}),
    },
  },
  plugins: [vue(), vuetify({ autoImport: true })],
})

@tumus2004
Copy link

tumus2004 commented May 12, 2023

I also have this issue but with Vite + Preact + Amplify

my config:

import commonjs from '@rollup/plugin-commonjs';
import rollupNodePolyFill from 'rollup-plugin-node-polyfills';
import { vanillaExtractPlugin } from '@vanilla-extract/vite-plugin';
import { defineConfig } from 'vite';
import preact from '@preact/preset-vite';

export default defineConfig({
    plugins: [preact()],
    root: './',
    publicDir: 'src',
    build: {
        outDir: 'dist',
        emptyOutDir: false,
        assetsDir: '',
        copyPublicDir: false,
        manifest: false,
        // Need to use the CommonJS plugin to correctly bundle all imports in a single import.
        rollupOptions: {
            plugins: [commonjs(), vanillaExtractPlugin(), rollupNodePolyFill()],
            input: 'src/v1/instant-woocommerce.js', // <--- don't worry about this, using for specific merchant configs due to an issue documented here: 
            output: [
                {
                    format: 'iife',
                    dir: 'dist',
                    entryFileNames: 'v1/[name].min.js', // make this "[name][hash].js" to include the hash
                },
            ],
        },
    },
    resolve: {
        alias: {
            './runtimeConfig': './runtimeConfig.browser', // <--- Attempted fix as above
            react: 'preact/compat', // <--- Preact specific
            'react-dom/test-utils': 'preact/test-utils', // <--- Preact specific
            'react-dom': 'preact/compat', // Must be below test-utils // <--- Preact specific
            'react/jsx-runtime': 'preact/jsx-runtime', // <--- Preact specific
        },
    },
});

I'll also include my tsconfig.json file:

{
    "compilerOptions": {
        "target": "ES6",
        "useDefineForClassFields": true,
        "module": "ESNext",
        "lib": ["ESNext", "DOM"],
        "moduleResolution": "Node",
        "strict": true,
        "resolveJsonModule": true,
        "isolatedModules": true,
        "esModuleInterop": true,
        "noEmit": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "noImplicitReturns": true,
        "types": ["vite/client", "@types/gtag.js", "node"],
        "jsx": "react-jsx",
        "jsxImportSource": "preact",
        "baseUrl": "./",
        "paths": {
            "react": ["./node_modules/preact/compat/"],
            "react-dom": ["./node_modules/preact/compat/"]
        }
    },
    "include": ["src", "main.ts"]
}

I recognise the post is mostly around vue + vite but I am getting the same build issues with preact + vite.

No troubleshooting as above has helped yet - would be very keen on some assistance

@brillout
Copy link

brillout commented Jun 4, 2023

This also affects many vite-plugin-ssr users.

@ErhardScampi
Copy link

ErhardScampi commented Jul 2, 2023

Still open in 2023 with newest Quasar (vite). and newest amplify:

Tried to use rollup-plugin-polyfill-node
but quasar.config.js runs in a node env. so I can't import it. require does not work either. Any ideas to manage it with quasar and vite somehow ?

This is the origin error when I run npx quasar build :
'request' is not exported by __vite-browser-external, imported by node_modules/@aws-sdk/client-cloudwatch-logs/node_modules/@aws-sdk/credential-provider-imds/dist/es/remoteProvider/httpRequest.js file: /Users/sc/dev/artbarrack/code/node_modules/@aws-sdk/client-cloudwatch-logs/node_modules/@aws-sdk/credential-provider-imds/dist/es/remoteProvider/httpRequest.js:4:9 2: import { ProviderError } from "@aws-sdk/property-provider"; 3: import { Buffer } from "buffer"; 4: import { request } from "http"; ^ 5: /** 6: * @internal /Users/sc/dev/artbarrack/code/node_modules/rollup/dist/shared/rollup.js:198 base = Object.assign(new Error(base.message), base);

@brnsnt
Copy link

brnsnt commented Aug 10, 2023

For Quasar I had to add it to the build section in quasar.config.js (extending the vite config didn't work).

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

The missing global definitions is added directly inside index.html

    <script>
      /* https://ui.docs.amplify.aws/vue/getting-started/troubleshooting */
      window.global = window;
      var exports = {};
    </script>

@movingelectrons
Copy link

ugh whatever I'm going back to CRA then.

@avorsterman
Copy link

For Quasar I had to add it to the build section in quasar.config.js (extending the vite config didn't work).

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

The missing global definitions is added directly inside index.html

    <script>
      /* https://ui.docs.amplify.aws/vue/getting-started/troubleshooting */
      window.global = window;
      var exports = {};
    </script>

Thanks! I'm using Quasar too and this solved the error.

@charlieforward9
Copy link

I was told during Amplify Office Hours that v6 introduced a fix for Vite environments that removes the need to add this resolve config:

resolve: {
      alias: {
        "./runtimeConfig": "./runtimeConfig.browser", //fix production build
      }
    }

The release of v6 may or may not address everything discussed in this issue, but it felt appropriate to share this update here.

@asmajlovicmars
Copy link

asmajlovicmars commented Nov 18, 2023

I was told during Amplify Office Hours that v6 introduced a fix for Vite environments that removes the need to add this resolve config:

resolve: {
      alias: {
        "./runtimeConfig": "./runtimeConfig.browser", //fix production build
      }
    }

The release of v6 may or may not address everything discussed in this issue, but it felt appropriate to share this update here.

@charlieforward9 v6 works perfectly out of the box with SvelteKit, just tested it today, but there's another problem with SSR, which I don't know how to solve yet, described it here: #12578 .

There's no more withSSRContext, so I need to figure out how to get cognitoUser on the server side... Otherwise, v6 looks good to me.

@charlieforward9
Copy link

Good to hear! It seems like this issue might be solved/closable if it resolved this issue.

@QuantumStatic
Copy link

We are working on removing the need for these manual configurations on Amplify, for now - for Vite customers can you try the workaround mentioned in this comment to see if that resolves build issues for you? kevinold/repro-vite-amplify@4d6b422

Thanks! this helped, here's my vite.config.vue

import { fileURLToPath, URL } from "node:url";

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  define: {
    global: {},
  },
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
      "./runtimeConfig": "./runtimeConfig.browser",
    },
  },
});

I was facing global not defined. This really helped. Thanks!

@nadetastic
Copy link
Member

With the release of the latest major version of Amplify (aws-amplify@>6), this issue should now be resolved! Please refer to our release announcement, migration guide, and documentation for more information.

If you are still facing this issue after upgrading to v6, please let us know with a reply back.

@TeoTN
Copy link

TeoTN commented Jan 1, 2024

I still saw it with:

    "aws-amplify": "6.0.9",
    "@aws-amplify/ui-react": "6.0.7",

adding the following to vite.config.ts solves it:

  optimizeDeps: {
    esbuildOptions: {
      define: {
        global: 'globalThis',
      },
    },
  },

Without this change, it still fails and the error clearly points to @aws-amplify/ui-react:
Screenshot 2024-01-01 at 13 42 36
Screenshot 2024-01-01 at 13 43 08

@nadetastic
Copy link
Member

@TeoTN thanks for your feedback, it seems that it may be specific to the UI library. Will do additional testing and confirm.

@reesscot
Copy link
Contributor

reesscot commented Jan 24, 2024

@TeoTN Can you share your full package.json file? I don't see how buffer could be coming from the @aws-amplify/ui-react package. My understanding is that buffer was a dependency of aws-amplify version 5 and was removed in aws-amplify version 6.

@nadetastic
Copy link
Member

Hi @TeoTN unfortunately, Im unable to reproduce this issue. Are you still experiencing the error? If so could you try to delete your node_modules and reinstall you packages and see if the error persists? If you still continue to see the error, It would be great to get your package.json so I can reproduce with the same dependencies you have.

@nadetastic
Copy link
Member

Hi @TeoTN - Im going to close out this issue as we have not heard back from you. If you are still experiencing this, please feel free to reply back and provide any information previously requested and we'd be happy to re-open the issue.

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Build Related to build issues dependencies Pull requests that update a dependency file feature-request Request a new feature
Projects
None yet
Development

Successfully merging a pull request may close this issue.