Reputation: 2991
I have the following in one of my project files:
const baas = process.env.DBID;
console.log('baas', baas);
If I run:
cross-env PORT=4000 NODE_ENV=production WEBPACK_CONFIG=browser_prod,server_prod webpack --colors
My server.js file looks like:
const baas = undefined;
console.log('baas', baas);
As expected. However, I want to be able to set the ID when I run the built app not when I build the app, ie:
DBID=someotherid node dist/server.js
So I need webpack to not convert const baas = process.env.DBID
to it's value at build time, but rather leave it as is, so the server.js
uses it's value at runtime.
How do I do this?
Note: if I manually edit the built server.js
and change undefined
to process.env.DBID
then the run script works and the app uses the env var from run time, but I don't want to edit files after building.
Upvotes: 1
Views: 1108
Reputation: 1032
I was able to prevent Webpack from converting process.env
by accessing it indirectly like this:
const processText = "process";
const _process = global[processText];
app.listen(_process.env.PORT || 2000);
You need to get process
indirectly instead of env
because the process
variable is defined by webpack to be something like /* provided dependency */ var process = __webpack_require__(/*! process/browser */ "process/browser");
Upvotes: 0
Reputation: 3322
You are using the wrong target.
By default, webpack builds the application to be run in the browser. This means it will mock native node functions like path
fs
and process
Your target is node, so there is no need to mock these.
Add this to your webpack.config.js
module.exports = {
target: 'node'
};
https://webpack.js.org/concepts/targets/#usage
Upvotes: 2
Reputation: 7748
What you need is process.argv
not process.env
:
// server.js
const baas = process.argv[0];
console.log('baas', baas);
Then:
node dist/server.js baas_value
For convenience, you can use this module https://www.npmjs.com/package/yargs
Upvotes: 1