Can I detect if my script is being processed by Webpack?
You could also do this -
typeof __webpack_require__ === 'function'
I'm guessing this might change at anytime so use with caution. :/
in Node.js global.global
is cycle reference, Webpack is not creating this cycle:
function is_node() {
return typeof global !== 'undefined' && global.global === global;
}
Put this in your webpack config under plugins:
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
APP_ENV: JSON.stringify('browser')
}
}),
With that you can check if you're running in a browser or not this way:
if (process.env.APP_ENV === 'browser') {
const doSomething = require('./browser-only-js');
doSomething();
} else {
const somethingServer = require('./server-only-js');
somethingServer();
}
if (process.env.APP_ENV !== 'browser') {
const somethingServer = require('./server-only-js');
somethingServer();
}
Because these environment variables get replaced during the build, Webpack will not include resources that are server-only. You should always do these kinds of things in an easy way, with a simple, direct compare. Uglify will remove all dead code.
Since you used a function before and the function is not evaluated during build, Webpack wasn't able to know what requires it could skip.
(The NODE_ENV
-variable should always be set to production
in production mode, since many libraries including React use it for optimisations.)