[SOLVED] How to set global property for react using esbuild

Issue

According to the docs using define is the suggested way of setting the env properties for a build.

When I run my app with I get a process is not defined error.

My esconfig is as follows:

        await build({
            entryPoints: ['./src/index.tsx'],
            outdir: './build',
            bundle: true,
            incremental: true,
            metafile: true,
            target: 'es6',
            loader: { '.png': 'file' },
            minify: !dev,
            sourcemap: 'inline',
            define: { 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development') },
            plugins: [
                sassPlugin(),
                svg(),
                copy({
                    resolveFrom: 'cwd',
                    assets: {
                        from: ['./public/*'],
                        to: ['./build2/*'],
                    },
                }),
                copy({
                    resolveFrom: 'cwd',
                    assets: {
                        from: ['./public/images/*'],
                        to: ['./build2/images/*'],
                    },
                }),
            ],
            watch: dev
                ? {
                        onRebuild: (error) => {
                            if (error) {
                                console.error(error);
                            } else {
                                console.log('rebuild done');
                            }
                        },
                  }
                : false,
        });

I’m also open to other ways of setting global properties to control the configuration.

Solution

I’ve resorted to writing a config/env file before the build starts.
My react app then just needs to know where the env file is located.

const config: IEnv = {
    ENV: process.env.NODE_ENV ? process.env.NODE_ENV : 'development',
    USE_EMU: process.env.USE_EMU === '1' ? true : false,
    USE_DEV: process.env.USE_DEV === '1' ? true : false,
    VERSION: process.env.VERSION ? process.env.VERSION : 'dev',
};
fs.writeFileSync('src/env.json', JSON.stringify(config), { encoding: 'utf8' });

Answered By – AyKarsi

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *