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