React Typescript + Vite + AWS Amplify 05.2023
Tags: vite, amplify, react, typescript
Published: 2023-05-08 20:43:10

As a developer, you're constantly looking for ways to improve your workflow and streamline your development process. One tool that has gained popularity recently is Vite, a blazing-fast build tool that promises faster development and build times compared to Create React App (CRA). In this blog post, we'll explore why you should consider using Vite instead of CRA, and highlight one common issue that developers face when connecting Vite to AWS Amplify.

First off, let's talk about Vite. Vite is a modern build tool that offers near-instantaneous hot module replacement (HMR) and fast development server startup times. It achieves this by using native ES modules in the browser and leveraging modern browser features such as lazy-loading and dynamic imports. In contrast, CRA uses a more traditional approach, relying on Webpack and Babel to bundle and transpile your code. While CRA is still a great tool, Vite's approach is more efficient, making it a compelling option for developers looking to optimize their workflow.

Now, let's address the issue of connecting Vite to AWS Amplify. AWS Amplify is a cloud-based service that provides a suite of tools for building and deploying web and mobile applications. While it's a powerful tool, some developers have reported difficulty connecting Vite to Amplify. The main issue is that Vite's dev server is not compatible with Amplify's default setup, which uses Webpack as the build tool. This can cause problems when trying to test your app locally before deployment.

Fortunately, there are workarounds for this issue, and in this blog post, we'll cover some of the most common solutions. By the end of this post, you'll have a better understanding of how to connect Vite with AWS Amplify, and why Vite is a strong alternative to Create React App.

So, whether you're a seasoned developer or just starting out, Vite is a tool that you should consider using. Its speed and efficiency can help you streamline your development process, and with the right configuration, it can integrate seamlessly with AWS Amplify. So, let's dive in and explore why Vite might be the right choice for your next project.

# How to set up Vite on React - Typescript for Amplify?

First, install Vite
```bash
# npm 6.x
npm create vite@latest my-react-app --template react-ts

# npm 7+, extra double-dash is needed:
npm create vite@latest my-react-app -- --template react-ts

# yarn
yarn create vite my-react-app --template react-ts

# pnpm
pnpm create vite my-react-app --template react-ts
```

Second, cd to your project root folder and install the dependencies by running `npm install` (if you are using npm) and start your app by running `npm run dev`
```bash
npm install
npm run dev
```

Third, modify your `index.html` by adding the following script before the closing body tag `</body>`
```html
<script>
    window.global = window;
    window.process = {
      env: { DEBUG: undefined },
    }
    var exports = {};
</script>
```

Fourth, update your `vite.config.ts` and add a resolve alias inside the `defineConfig({})` as seen below. You need to add the `build output` so Amplify would know where to get the build target of your application.
```javascript
export default defineConfig({
  plugins: [react()],
  resolve: {
      alias: [
      {
        find: './runtimeConfig',
        replacement: './runtimeConfig.browser',
      },
    ]
  },
  //Add build if you are going to use a Git-based (Github or CodeCommit) deployement
  build: {
    outDir: "build",
  }
})
```
* if build is not included inside `defineConfig({})` the application will only work on Amplify manual deployment. In order for the Git-based (CI/CD pipeline) deployment to work, `build output` must be present. 
```bash
 build: {
    outDir: "build",
  }
```

Finally, update your `tsconfig.json` file and add `skipLibCheck: true` under `compilerOptions`.
```bash
    "compilerOptions": {
        "skipLibCheck": true,
    }
...
```

# IMPORTANT!!! 

When initializing your backend on Amplify `amplify init` (https://docs.amplify.aws/start/getting-started/setup/q/integration/react/) make sure you select `No` when asked `Initialize the project with the above configuration?`
```bash
? Enter a name for the project reactamplified
The following configuration will be applied:

?Project information
| Name:  reactamplified
| Environment: dev
| Default editor: Visual Studio Code
| App type: javascript
| Javascript framework: react
| Source Directory Path: src
| Distribution Directory Path: build
| Build Command: npm run-script build
| Start Command: npm run-script start

? Initialize the project with the above configuration? No

```
Amplify will ask you to prompt your response manually. Once you get to the `Build Command` question, type

```bash
npm run build
```
and for the `Start Command`, type
```bash
npm run dev
```
This is very important!
```bash
| Start Command: npm run-script start
```
Since you are using `Vite`, you need to modify the start and build command for Amplify to mirror your package.json. Check your package.json and you will see that `npm run dev` will start your application not `npm run start`
```bash
"scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "lint": "eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
```
Finally you should have something like this:
```bash
| Name:  reactamplified
| Environment: dev
| Default editor: Visual Studio Code
| App type: javascript
| Javascript framework: react
| Source Directory Path: src
| Distribution Directory Path: build
| Build Command: npm run build
| Start Command: npm run dev
```

For information on how to set up Amplify please visit https://docs.amplify.aws/start/q/integration/react/



# Let me repeat my self

* if `build` is not included inside `defineConfig({})` of your `vite.config.ts` the application will only work on Amplify manual deployment. In order for the Git-based (CI/CD pipeline) deployment to work, `build` output must be present. 
```javascript
export default defineConfig({
  plugins: [react()],
  resolve: {
      alias: [
      {
        find: './runtimeConfig',
        replacement: './runtimeConfig.browser',
      },
    ]
  },
  build: {
    outDir: "build",
  }
})
```
Go to your aws console > Amplify > your app > Build Settings > amplify.yml and check if all settings are correct. Make sure that the `build commands` is `npm run build` and `artifacts baseDirectory` is set to `build`
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vo198x8zw6p0c1lnhrnv.png)

# Troubleshooting: Declaration file for aws-exports
When adding the following code to your index.ts (or main.ts; I usually rename my main.ts to index.ts just for my sanity)
```javascript
import { Amplify } from 'aws-amplify';
import awsExports from './aws-exports';
Amplify.configure(awsExports);
```
and see this error:
```bash
Could not find a declaration file for module './aws-exports'. 'aws-exports.js' implicitly has an 'any' type.
```
Create a aws-exports.d.ts file on the same level as aws-exports with the following content:
```javascript
declare module './aws-exports' {
    const awsExports: unknown | never;
    export default awsExports;
}

export = awsmobile; declare const awsmobile: any;
```

or

```javascript
declare const awsmobile: Record<string, any>
export default awsmobile;
```

This code will fix your issue.

# Why is Vite a strong alternative to Create React App?


###Fast Development and Build Speed
One of the main advantages of Vite is its fast development and build speed. Vite uses a modern development server that leverages ES modules to speed up the development process. This means that changes to your code are reflected immediately in the browser, without the need for a full rebuild. In contrast, CRA uses a more traditional build system that requires a full rebuild every time you make changes to your code. This can slow down your development process, especially if you're working on a large project.

Vite also has a fast build speed, thanks to its use of a highly optimized build pipeline. Vite's build pipeline uses Rollup under the hood, which is known for its excellent performance. This means that you can generate a production build of your application much faster with Vite than with CRA.

###Flexible Configuration
Another advantage of Vite is its flexible configuration. Vite allows you to configure your project using a simple configuration file, similar to CRA. However, Vite's configuration file is much simpler and easier to understand than CRA's. This makes it easier to customize your project to meet your specific needs.

In addition, Vite supports a wide range of plugins that can extend its functionality. This means that you can easily add new features to your project, such as support for TypeScript, CSS preprocessors, and more.

###Support for Multiple Frameworks
Vite is not limited to React. It also supports other popular front-end frameworks, such as Vue.js and Svelte. This means that you can use Vite as a universal build tool for all your front-end projects, regardless of which framework you're using.

In contrast, CRA is designed specifically for React projects. While it's possible to modify CRA to support other frameworks, it requires additional configuration and setup.

###Conclusion
In summary, Vite is becoming a popular choice for building React applications due to its fast development and build speed, flexible configuration, and support for multiple frameworks. While CRA is still a reliable choice for building React projects, Vite offers a more modern and flexible approach that many developers are finding appealing. If you're looking for a fast and flexible build tool for your next React project, consider giving Vite a try.


_Please leave a comment below if you like these kind of blog post._