DEV Community

Cover image for Setup React App with esbuild
Dhruvang Gajjar
Dhruvang Gajjar

Posted on • Updated on

Setup React App with esbuild

Usally we create our react application using "create-react-app" which takes too much time to setup and installing packages. Also It takes more time start the server.

ESBuild is the solution of that frustrating issue.

When we setup react application with "create-react-app", it will install many packages which takes more time. Also webpack is slow compared to esbuild.

Let's start with initiating project by npm init. Thereafter install react and react-dom using following command.

npm i react react-dom
Enter fullscreen mode Exit fullscreen mode

Once react dependencies have been added, install dev dependencies esbuild and live-server. Here live-server will be used to run the server.

npm i esbuild live-server --save-dev
Enter fullscreen mode Exit fullscreen mode

Once all the dependencies have been installed, create public and src folder. All the react files should be placed inside src folder and index.html file should be placed inside public folder.

Folder Structure should be look like this.

Image description

Now create a server.js file in which we will define build related code.

Code of server.js should be as follows:

const { build } = require("esbuild"),
    liveServer = require("live-server");

build({
    entryPoints: ['./src/index.js'],
    outfile: './public/bundle.js',
    bundle: true,
    loader: {
        '.js': 'jsx'
    },
    watch: {
        onRebuild(error, result) {
            if (error) console.error('watch build failed:', error)
            else console.log('watch build succeeded:', result)
        },
    },
}).then(result => {
    liveServer.start({
        port: 8000,
        host: 'localhost',
        root: "public",
        open: true,
        watch: "everything",
        ignore: 'scss,my/templates',
        file: "index.html",
        wait: 1000,
        mount: [['/components', './node_modules']],
        logLevel: 2,
        middleware: [function (req, res, next) { next(); }]
    });
    console.log('watching...', result)
})
Enter fullscreen mode Exit fullscreen mode

And That's all. Now just add your react code inside src folder and us the bundle.js in public folder.

Sharing Github link for reference.

Top comments (0)