Environment variable from webpack to dev and production

I am new to the world using building tools like Webpack and its relatives, so maybe this question is a bit noobish, but please understand me.

background: I am developing a client-side web application (using actionjs + redux) and using webpack as a build tool and dev server loader. Now I have to do some lines of code only in the dev environment (write and stuff). Therefore, I saw on the web using the webpack.DefinePlugin plugin to set the variable process.env.NODE_ENV , and the code looks like this:

 plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development') }) ] 

Then, if varibale NODE_ENV not set on my machine (which is currently missing), it is automatically installed on development. I'm right?

How about a production machine? do I need to set this env variable to 'production' in the /etc/environment file?

The question then becomes, how does webpack know what NODE_ENV is when I serve the application? Is it compiled when I build on the production machine and install the bundle.js built-in package? ( $ webpack --progress -p )

Another question: how to enable / disable functions in a development or development environment? just execute the if if statement as follows:

 if(process.env.NODE_ENV == 'development'){ console.log('this is visible in development'); } 

And last, if this is what webpack really does, does this piece of code rewrite the bundle.js inline package? if so, is it visible to the end user? is there anything with this?

Hope this is not much, thanks a bunch!

+5
source share
1 answer

On a working machine, you can create your scripts with the command

 NODE_ENV=production webpack 

On the other hand, passing this variable to /etc/environment also a solution.


process.env.NODE_ENV converted to a static string in bundle.js

for example, if you run NODE_ENV=production webpack in this snippet

 if(process.env.NODE_ENV == 'development'){ console.log('this is visible in development'); } 

in bundle.js you will find (edited)

 if ('production' == 'development') { console.log('this is visible in development'); } 

 if (false) { // 'production' == 'development' console.log('this is visible in development'); } 

So, in accordance with the question of enabling / disabling functions, your code is valid.


If you want to remove the condition body, if it is false (as in the above example, you do not want to show console.log('this is visible in development'); in the production environment), you should use

 new webpack.optimize.UglifyJsPlugin() 

It will remove all your if statements with the false condition.

+10
source

All Articles