DEV Community

Akira Abe
Akira Abe

Posted on • Edited on

Vite+React+Amplify initial setup!

Purpose of this article.

I want to try out the very fast build tool Vite!
I wanted to know how to start a project with my usual React+Amplify configuration.
This is my personal note.

Software versions

The main software versions are listed below.

  • node v18.9.0
  • TypeScript 4.6.4
  • Vite 3.1.0
  • React 18.2.0

Summary ahead of time

The official Amplify page guides how to use create-react-app when linking Amplify and React.
When using Vite, there are some parts that do not work as they are, so it is necessary to deal with errors.
This section outlines the errors and how to handle them. (Details are described below).

amplify pull gives me an error



βœ– There was an error initializing your environment.
Failed to pull the backend.
πŸ›‘ Must use import to load ES Module: /Users/xxxxxxxx/my_first_vite/src/aws-exports.js
require() of ES modules is not supported.
require() of /Users/xxxxxxxx/my_first_vite/src/aws-exports.js from /snapshot/repo/build/node_modules/amplify-frontend-javascript/lib/frontend-config-creator.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.



Enter fullscreen mode Exit fullscreen mode

We need to treat this error like this.

  • Rename aws-exports.js to aws-exports.ts
  • Remove the line "type": "module" from package.json

Additional Info.
I got a message from Discord community, below!

For what it's worth, the ESM issue (where we have to remove "type": "module") is fixed with the latest version version of the CLI, 10.2.3

Error with yarn dev.



Uncaught ReferenceError: global is not defined


Enter fullscreen mode Exit fullscreen mode

The following actions will be taken
Change index.html

amplify publish causes error



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/@aws-sdk/credential-provider-node/node_modules/@aws-sdk/credential-provider-imds/dist/es/remoteProvider/httpRequest.js


Enter fullscreen mode Exit fullscreen mode

Change vite.config.ts

Development Procedure

Assuming that node, AmplifyCLI, and Vite have already been installed, we will start with project creation.

  • Create a React project using Vite
  • Create an Amplify project
  • Initialize the app
  • Do the data model integration
  • Hosting with Amplify CLI

Create a React project using Vite

The commands are as follows.



yarn create vite my_first_vite --template react-ts


Enter fullscreen mode Exit fullscreen mode

"my_first_vite" is the name of the project, and can be any value you wish.
--template react-ts applies the React TypeScript template.
Please also read the official website [1], which explains this command.

Creating an Amplify project

There are multiple ways to create an Amplify project, but here we will use AmplifyStudio.

Creating a project in the AWS Management Console

First, select AWS Amplify (hereafter referred to as Amplify) from the AWS Management Console and click
Select [New app]>[Build an app] from the upper right corner of the screen as shown below.

Amplify Studio new app

Next, enter the App name on the following screen and click "Confirm deployment".
In this case, the name is "my_first_vite", but you can use any name you like.

Confirm deployment

The figure below shows the waiting screen during deployment. (It takes 5 to 6 minutes.)

now deploy is going.

When the screen transitions to the following, click "Launch Studio" to launch Amplify Studio.

Now let's launch the studio

What to do after launching Amplify Studio

Amplify Studio allows you to configure various backend resources.
It is not the purpose of this article to introduce them in detail, so we will only define a simple data model here.
Other things can be done, such as generating a UI in conjunction with Figma or using Cognito to incorporate authentication, but please refer to another article [2] or the AWS tutorial [3].

Defining the Data Model

Define the data model as follows. When you are done, press [Save and Deploy].

Let's launch data model view

This is the screen waiting to be deployed. This process will take some time because AppSync and DynamoDB will be created by CloudFormation at this time. (It may take about 10 minutes).

deploy

When a deployment is complete (successful), you will be taken to the following screen. (Press "Done" to close the screen.

Image description

Here, (2) Update your app code will guide you through an example source code when you select the programming language, model, operation, etc. (This is a simplified version, so please refer to the document [4] for details. (This is a simplified version, so you should check the documentation [4] for details)

Pull Amplify materials locally

In the React project created by yarn create, run the amplify pull command as follows.
(Here we are working in the VSCode terminal)

An error will occur, but how to deal with it is described later.



 amplify pull
? Select the authentication method you want to use: AWS profile

For more information on AWS Profiles, see:
https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html

? Please choose the profile you want to use default
? Which app are you working on? xxxxxxxxxxxxxx                              
Backend environment 'staging' found. Initializing...
? Choose your default editor: Visual Studio Code
? Choose the type of app that you're building javascript
Please tell us about your project
? What javascript framework are you using react
? Source Directory Path:  src
? Distribution Directory Path: dist *** This is "build" by default, but we have explicitly changed it. ***
? Build Command:  npm run-script build
? Start Command: npm run-script start
βœ… GraphQL schema compiled successfully.

Edit your schema at /Users/xxxxxxxx/my_first_vite/amplify/backend/api/myfirstvite/schema.graphql or place .graphql files in a directory at /Users/xxxxxxxx/my_first_vite/amplify/backend/api/myfirstvite/schema
Successfully generated models. Generated models can be found in /Users/xxxxxxxx/my_first_vite/src
? Do you plan on modifying this backend? Yes
β ™ Fetching updates to backend environment: staging from the cloud.βœ… GraphQL schema compiled successfully.

Edit your schema at /Users/xxxxxxxx/my_first_vite/amplify/backend/api/myfirstvite/schema.graphql or place .graphql files in a directory at /Users/xxxxxxxx/my_first_vite/amplify/backend/api/myfirstvite/schema
βœ” Successfully pulled backend environment staging from the cloud.
βœ– There was an error initializing your environment.
Failed to pull the backend.
πŸ›‘ Must use import to load ES Module: /Users/xxxxxxxx/my_first_vite/src/aws-exports.js
require() of ES modules is not supported.
require() of /Users/xxxxxxxx/my_first_vite/src/aws-exports.js from /snapshot/repo/build/node_modules/amplify-frontend-javascript/lib/frontend-config-creator.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename aws-exports.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /Users/xxxxxxxx/my_first_vite/package.json.



Enter fullscreen mode Exit fullscreen mode

An error occurs. So, we will respond according to the message.

  • Rename aws-exports.js to aws-exports.ts. (Note that aws-eports.js is created for each amplify pull, so you need to rename it for each pull.)
  • Remove the line "type": "module" from package.json.


{
  "name": "my_first_vite",
  "private": true,
  "version": "0.0.0",
-  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@types/react": "^18.0.17",
    "@types/react-dom": "^18.0.6",
    "@vitejs/plugin-react": "^2.1.0",
    "typescript": "^4.6.4",
    "vite": "^3.1.0"
  }
}


Enter fullscreen mode Exit fullscreen mode

After making the above modifications, rerun amplify pull.

Set up the initial configuration of the app

At this point, we will launch the application once.



## Install dependent modules
yarn install

# Start the development server
yarn dev


Enter fullscreen mode Exit fullscreen mode

The application at this point looks like the following

Image description

Change the application to use Amplify.

The file to be changed is as follows. (The project root is listed as the starting point)

  • package.json
  • src/index.css
  • src/main.tsx
  • src/App.tsx

Include a diff in package.json. (After making changes, run yarn install.)

package.json



{
  "dependencies": {
+    "@aws-amplify/ui-react": "^3.5.4",
+    "aws-amplify": "^4.3.36",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
}


Enter fullscreen mode Exit fullscreen mode

Update index.css with the following



@import url('https://fonts.googleapis.com/css2?family=Inter:slnt,wght@-10..0,100..900&display=swap');
body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
    monospace;
}



Enter fullscreen mode Exit fullscreen mode

main.tsx below.



import React from 'react'
import ReactDOM from 'react-dom/client'
+import { AmplifyProvider } from '@aws-amplify/ui-react';
+import { Amplify } from 'aws-amplify';
import App from './App'
import './index.css'
+import config from './aws-exports';

+Amplify.configure(config);

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
-  <React.StrictMode>
+  <AmplifyProvider
     <App />
+  </AmplifyProvider>
-  </React.StrictMode>
)


Enter fullscreen mode Exit fullscreen mode

App.tsx below.



import type { FC } from 'react';
import { Amplify } from 'aws-amplify';
// eslint-disable-next-line import/extensions
import '@aws-amplify/ui-react/styles.css';
import awsExports from './aws-exports';

Amplify.configure(awsExports);

const App: FC = () => {
  return (
    <h1>
      Hello Amplify+Vite!
    </h1>
  );
}

export default App;



Enter fullscreen mode Exit fullscreen mode

However, when I start the development server in this state (yarn dev), I get the following error
Image description

We update "index.html" as follows. (list the differences)



<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React + TS</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
+    <script>
+      window.global = window;
+      window.process = {
+        env: { DEBUG: undefined },
+      };
+      var exports = {};
+    </script>
  </body>
</html>


Enter fullscreen mode Exit fullscreen mode

The following initial screen will appear in your browser as a result so far.

Image description

Source code at this point

https://github.com/akiraabe/my_first_vite/tree/Initial

Data Model Linkage.

Please refer to the source code as it is time-consuming to describe the steps to link with the data model.

https://github.com/akiraabe/my_first_vite/tree/UsingAmplify
Only data registration and listing are performed.

Hosting with Amplify CLI

Follow the steps below for hosting. (The reason I use Amplify CLI instead of AWS Management Console is because I want to install WAF on CloudFront.)

  • amplify add hosting
  • amplify publish

amplify add hosting

Execute the following command.



amplify add hosting
βœ” Select the plugin module to execute Β· Amazon CloudFront and S3
? Select the environment setup: PROD (S3 with CloudFront using HTTPS)
? hosting bucket name myfirstvite-xxxxxxxxxxxx-hostingbucket
Static webhosting is disabled for the hosting bucket when CloudFront Distribution is enabled.

You can now publish your app using the following command:
Command: amplify publish

Enter fullscreen mode Exit fullscreen mode




amplify publish

Execute the following command

However, this will fail and will be corrected later.



amplify publish

'request' is not exported by __vite-browser-external, imported by node_modules/@aws-sdk/credential-provider-node/node_modules/@aws-sdk/credential-provider-imds/dist/es/remoteProvider/httpRequest.js
file: /Users/xxxxxxxxmy_first_vite/node_modules/@aws-sdk/credential-provider-node/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/@aws-sdk/credential-provider-node/node_modules/@aws-sdk/credential-provider-imds/dist/es/remoteProvider/httpRequest.js

Enter fullscreen mode Exit fullscreen mode



error handling

Make the following modifications to vite.config.ts. Then re-run amplify publish.



import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
+ resolve: {
+ alias: [
+ { find: './runtimeConfig', replacement: './runtimeConfig.browser' },
+ { find: '@', replacement: '/src' },
+ ],
+ },
plugins: [react()]
})

Enter fullscreen mode Exit fullscreen mode




Impressions

Vite is comfortable to use because the local development server starts up explosively fast (although the code base is not so big this time).
It does take some initial setup, but I felt it was worth it!

Footnotes

[1] Scaffolding your first vite project
[2] AmplifyStudio & Figma
[3] AWS AmplifyStudio Tutorial Blog
[4] Amplify DataStore Docs

Top comments (6)

Collapse
 
jsancho profile image
Jaume Sancho

Hi, it seems like you've missed to paste the details for the last error, the one to fix amplify publish.
Incidentally, I get this same error when I try to do a vite build

you've written
"Make the following modifications to vite.config.ts. Then re-run amplify publish."
but the actual changes to vite.config.ts are missing :O

thanks

Collapse
 
akiraabe profile image
Akira Abe

Thank you for your feedback.
And, I'm sorry for my late reaction.

Collapse
 
jsancho profile image
Jaume Sancho

Seems like this is a known issue, as seen here
github.com/aws/aws-sdk-js/issues/3673

this workaround has worked for me
github.com/aws/aws-sdk-js/issues/3...

Collapse
 
bernhardsmuts profile image
BernhardSmuts

I am really trying to get on the Vite train, but the extra config needed for Everything from ESlint to AWS Amplify keeps pushing me back to CRA, not sure I understand have Vite is supposed to be better?

Collapse
 
marcellobonini profile image
Krzysztof Imbierowicz

I do have an error after doing everything just like you: Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "application/octet-stream". Strict MIME type checking is enforced for module scripts per HTML spec.

Collapse
 
elainemartis profile image
elainemartis

I'm facing the same error. Were you able to find a solution yet?