Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

375
Views
How can I prevent a specific function from being included in a bundle?

Let's say I have some JavaScript code that I want to use on both a Node server and on a browser client. It defines a couple classes that would be helpful on both sides. I would like to prevent myself from having to write the common code twice or splitting the client and server specific code into subclasses.

Is there a way in webpack (or any other packager) to mark specific functions as ignored?

For example, in the following snippet, the comment /* webpack-dont-pack */ prevents the function serverOnly from being compiled into the client build (similar to eslint or ts ignore comments).

class SomeClass {
  constructor(arg1, arg2) {
    // init
  }

  commonFunction(arg1) {
    // do something
  }

  /* webpack-dont-pack */
  serverOnly(serverArg) {
    // how can this function be excluded from a specific webpack bundle?
  }
}

Preferably, the bundle for the client would exclude the function serverOnly and the server build would include this function. Note, the use of "client" and "server" is arbitrary in this case. It is more about can two bundles have different code.

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

You could use inheritance and conditional exports in the class' module, sth along those lines:

class BaseClass {}

class ClientClass extends BaseClass {}

class ServerClass extends BaseClass {
    method() {
        console.log("I have my methods");
    }
}

const Foo = (process.env.production === "true" ? ServerClass : ClientClass);

export { Foo as MyClass };

The method (or rather the ServerClass) should be treeshaken out of the bundle if the production environment method isn't set to "true". I think.

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!