• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

269
Vistas
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.

almost 3 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

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.

almost 3 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda