AWS Amplify: getting started with Vite

martin rojas - Mar 28 '23 - - Dev Community

When it comes to starting a new React app on Amplify, the Amplify docs suggest using Create React App. But now, there's a new player in town: Vite. Vite is a great alternative for creating single-page React applications. However, Create React App has some of the best pre-configured and battle-tested browser polyfills for web applications that need broad support across browsers, particularly in corporate environments.

Despite this, for projects that want to embrace the latest and greatest, Vite provides some definite advantages. However, some changes to the default Vite project start need to be done to support the use of the AWS SDK. Issue #3673.

Scaffolding Your Vite Project

To start off with typescript use --template react-ts

With NPM:

$ npm create vite@latest my-vue-app --template react
Enter fullscreen mode Exit fullscreen mode

With Yarn:

$ yarn create vite my-vue-app --template react
Enter fullscreen mode Exit fullscreen mode

With PNPM:

$ pnpm create vite my-vue-app --template react
Enter fullscreen mode Exit fullscreen mode

Then follow the prompts!

Once the project is created there add the following

index.html in the <body> tag

<script>
      // AWS Amplify needs this to work. See https://github.com/aws/aws-sdk-js/issues/3673
      const isBrowser = () => typeof window !== "undefined";
      const isGlobal = () => typeof global !== "undefined";
      if (!isGlobal() && isBrowser()) {
        var global = window;
      }
    </script>
Enter fullscreen mode Exit fullscreen mode

Also, add a resolve object to the vite.config.js

resolve: {
    alias: {
      "./runtimeConfig": "./runtimeConfig.browser",
    },
  },
Enter fullscreen mode Exit fullscreen mode

Micah Redwood created a repository with how your project should look after following these steps and can be used as a reference.

https://github.com/micah-redwood/vite-amplify-demo

However, if you have an existing create-react-app and would like to migrate to Vite, the process is simple. I have found 2 great articles that break them the steps and once the project is using Vite it will still need the 2 code fixes to be able to work on Amplify.

Migrating your Create React App project to Vite

Migrating from Create React App (CRA) to Vite

. . . . . . . . . . . . . . . . . .
Terabox Video Player