Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

javascript - How to strip testing code when React JS is minified by for production?

In my React functional component, I use useEffect to do some debug logging, but I only want it when I am running in a non --production build.

// something like
if (process.env.NODE_ENV !== 'production') {
  // I want the contents of this block removed on production builds, but it is inside a function
  useEffect(() => {
    console.log("authState changed", AuthStates[authState]);
  }, [authState]);

  useEffect(() => {
    console.log("authToken changed", authToken);
    if (tokenExpiresOn) {
      console.log(
        `token expires in ${(tokenExpiresOn - Date.now()).toLocaleString()}ms`
      );
    }
  }, [authToken]);

  useEffect(() => {
    if (tokenExpiresOn) {
      console.log(
        `token expires in ${(tokenExpiresOn - Date.now()).toLocaleString()}ms`
      );
    } else {
      console.log("tokenExpiresOn cleared");
    }
  }, [tokenExpiresOn]);
}
question from:https://stackoverflow.com/questions/65861526/how-to-strip-testing-code-when-react-js-is-minified-by-for-production

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can not declare hooks conditionally. You can declare on the top level and you can put your business logic inside the hook, e.g below.

useEffect(() => {
   if (process.env.NODE_ENV !== 'production'){
    console.log("authToken changed", authToken);
    if (tokenExpiresOn) {
      console.log(
        `token expires in ${(tokenExpiresOn - Date.now()).toLocaleString()}ms`
      );
    }
 }
  }, [authToken]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...