'How to set global property for react using esbuild
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 1:[1]
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' });
Solution 2:[2]
You are getting process is not defined
error because you actually do not define process
in define
option, you do define process.env.NODE_ENV
.
It may be counterintuitively but it is how define
option is used. It doesn't actually defines variable and just replaces all tokens that look like define
key with corresponding value.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | AyKarsi |
Solution 2 | Mikhail Sereniti |