How to Bundle your React App in a Single File

H

Learn how to bundle all the JavaScript and CSS files generated by the React App build and combine them into a single file.

Published in: JavaScript

When you create a production build for your React App, the output folder contains the main index.html file and associated JavaScript and CSS files are added in the /static/js and /static/css folders respectively.

React Build Output

If you are to combine all these JS and CSS files of React App in a single bundle, you can use gulp. Here’s how:

Go to the command line and install the gulp packages as dev dependencies in your package.json file.

npm install --save-dev gulp gulp-inline-source gulp-replace

Next, create a .env file in your project root folder and set the following environment variable to disable source maps.

INLINE_RUNTIME_CHUNK=false
GENERATE_SOURCEMAP=false
SKIP_PREFLIGHT_CHECK=true

Next, create a gulpfile.js file in the root folder.

const gulp = require('gulp')
const inlinesource = require('gulp-inline-source')
const replace = require('gulp-replace')

gulp.task('default', () => {
    return gulp.src('./build/*.html')
        .pipe(replace('.js"></script>', '.js" inline></script>'))
        .pipe(replace('rel="stylesheet">', 'rel="stylesheet" inline>'))
        .pipe(inlinesource({
            compress: false,
            ignore: ['png']
        }))
        .pipe(gulp.dest('./build'))
});

The gulp task will add the inline attribute to the <script> and the <link> tags. The inlinesource module will read these inline attributes in the html file and replace them with the actual content of the corresponding files.

Run npm run build or npx react-scripts build to create an optimized production build for your React App and then run the command npx gulp to bundle all the JS and CSS files in the static build folder into the single main html file.

React App Inline

Published in: JavaScript

Looking for something? Find here!

Meet the Author

Web Geek, Tech Columnist
A
Amit Agarwal

Amit Agarwal is a Google Developer Expert in GSuite and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India. Read more on Lifehacker and YourStory

Get in touch