Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I mark code blocks as production or development only with webpack?

I'm building React components and in order to make my code more developer friendly, I'm including things like:

componentDidMount() {
  setTimeout(() => {
    if (!this.props.setupComplete) 
      console.warn("ComponentX might be stuck. This may mean you forget such and such.");
  }, setupCheckDelay);
}

The idea is to help developers pinpoint common mistakes more quickly. Is there a way to mark this code to tell webpack to simply leave it out of a production build? Or only include it in a development build? E.g., I want something like:

// build-hint-development-only
... my checking code
// end-build-hint

such that in a production build, to the code is left out entirely. My goal is to reduce final code size (and not simply avoid execution).

I've googled around a bit but haven't found anything. I gather I could use dynamic imports + environment variables, and then re-arrange the code such that the development checks are done and a wrapper HOC or something that just never gets included in the development build, but that seems fragile and complex for something pretty simple. The other option would be to put a pre-processor in front of the webpack build that would make a copy of the code without the marked 'dev only' sections, but would add a whole other layer to the process.

like image 912
zanerock Avatar asked Jun 23 '18 03:06

zanerock


2 Answers

The process.env.NODE_ENV variable will be set by webpack according to the current mode. Use it like this:

if (process.env.NODE_ENV === 'production') {
  // Code will only appear in production build.
}

if (process.env.NODE_ENV !== 'production') {
  // Code will be removed from production build.
  console.log("Looks like you're a developer.");
}

Documentation: webpack - Production

like image 117
matthiasgiger Avatar answered Nov 17 '22 07:11

matthiasgiger


You can use environment variables.

componentDidMount() {
  setTimeout(() => {
    if (process.env.NODE_ENV !== 'production') 
     console.warn("ComponentX might be stuck. This may mean you forget such and such.");
   }, setupCheckDelay);
  }

https://webpack.js.org/guides/environment-variables/

like image 31
Alexander Kuzmin Avatar answered Nov 17 '22 08:11

Alexander Kuzmin