Welcome to the Vite JS Deployment to AWS S3 tutorial! In this guide, we'll walk you through the process of deploying your Vite project to Amazon Web Services (AWS) S3. Let's get started!
Before we dive in, make sure you have the following prerequisites:
A Vite project follows a specific structure. Here's a brief overview:
my-vite-project
|- node_modules
|- public
|- src
|- vite.config.js
Vite is a modern front-end build tool that offers faster development and production-like build times. It's a great choice for building scalable and efficient web projects.
Create bucket, provide a unique name, and click Create.Bucket policy section and update it with the following JSON policy:{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": [
"s3:GetObject"
],
"Resource": "arn:aws:s3:::YOUR_BUCKET_NAME/*"
}
]
}Replace YOUR_BUCKET_NAME with the name of your S3 bucket.
npm install vite-plugin-react-refresh @vitejs/plugin-react @vitejs/plugin-vuevite.config.js:import { createVuePlugin } from '@vitejs/plugin-vue'
import reactRefresh from '@vitejs/plugin-react-refresh'
export default ({ command }) => {
return {
plugins: command === 'build'
? [reactRefresh(), createVuePlugin()]
: [reactRefresh()]
}
}npm run buildThe production build process includes minification, source mapping, and optimizations to improve the efficiency and size of the output files.
aws-s3 package:npm install aws-sdkdeploy.js in the root of your project:const { S3Manager, Uploader } = require('aws-s3');
const path = require('path');
const fs = require('fs');
const { viteStaticCopy } = require('vite-static-copy');
const bucketName = 'YOUR_BUCKET_NAME';
const region = 'us-west-2';
const accessKeyId = 'YOUR_ACCESS_KEY_ID';
const secretAccessKey = 'YOUR_SECRET_ACCESS_KEY';
const s3 = new S3Manager({
region,
accessKeyId,
secretAccessKey,
});
async function sync() {
const { distDir } = await viteStaticCopy({
root: path.resolve(__dirname, 'dist'),
outDir: path.resolve(__dirname, 'build'),
copyPublicDir: false,
});
const uploader = new Uploader({ s3 });
const promises = fs.readdirSync(distDir).map((file) => {
const filePath = path.join(distDir, file);
const s3Params = {
Bucket: bucketName,
Key: file,
Body: fs.readFileSync(filePath),
};
return uploader.upload(s3Params).promise();
});
await Promise.all(promises);
console.log('Deployment complete!');
}
sync();Replace YOUR_BUCKET_NAME, us-west-2, YOUR_ACCESS_KEY_ID, and YOUR_SECRET_ACCESS_KEY with your AWS S3 bucket details.
node deploy.jsYour Vite project should now be deployed to AWS S3.
The deployment script uses the vite-static-copy package to copy the production-built files to a temporary directory (build) and then uploads those files to your S3 bucket.
index.html) from the bucket properties.If everything went well, you should see your Vite project live!
That's it! You've successfully deployed your Vite project to AWS S3. Happy coding! 🎉