There are many ways you can get code into an S3 bucket, especially if you have a build/deploy server. But what do you do when you do not have one? One possible solution is to use Gulp to build/deploy the React application and publish to an S3 bucket.
Before you get started I am going to make a few assumptions.
- You already know basic Gulp.js usage, if not details on this here
- You already have a React application, if not details on this here
- You already have an AWS account setup, if not details on this here
- You will also need to make sure you have your CLI configured w/ credentials. See here for details
- You already have a build npm task in your package.json file, if not look here
To get started, the first thing we are going to need to install a few NPM packages
npm install --save-dev aws-sdk gulp-run run-sequence
After you have the npm packages installed we will need to start working on your gulpfile.js changes
Add the reference to the package we added
const run = require('gulp-run'); const AWS = require('aws-sdk'); const runSequence = require('run-sequence');
After we reference our packages we need to create an instance of the S3 object, this will be used to push the files into our S3 bucket.
const s3 = new AWS.S3({apiVersion: '2006-03-01'});
Now that we have all the prerequisite stuff out of the way, time to get down to business.
We are going to create 3 tasks.
- deploy- -> This will be used to kick off the entire process.
- build-react -> This will be used to call the npm build (from your package.json)
- copy-to-bucket -> This is what will do the actual deployment to S3
- This gulp task is going to make us of the aws skd
s3 cp
command.
- This gulp task is going to make us of the aws skd
gulp.task('build-react', buildReact); gulp.task('copy-to-bucket', copyToS3Bucket); gulp.task('deploy', function(done){ // we use runSequence to ensure that our tasks // sync vs asynch runSequence( 'build-react', 'copy-to-bucket', done); }); function buildReact() { return run("npm run build").exec(); } function copyToS3Bucket() { const pathToS3Bucket = "s3://the-name-of-my-bucket"; // I am using the --recurisve here in order top copy all the files in my build folder const publishPackageCommand = "aws s3 cp ./path-to-build-folder " + pathToS3Bucket + " --recursive"; return run(publishPackageCommand).exec(); }
After you have implemented the changes above you can run gulp on the command line and watch the magic unfold.
gulp deploy
If you would like to see a full working copy of my gulpfile.js checkout this gist.
Pingback: Interesting links of the week (02/12 – 02/18, 2018) – same stuff, different day