I want to use webpack to bundle a NodeJS application that exports functions to be used by other projects. However, when i export functions in src/index.js
that are not used anywhere else inside the bundle, they are omitted from the actual bundle in dist/index.bundle.js
.
From webpack’s documentation I learned that this behaviour is expected, following the Tree Shaking principle to omit “dead code”.
I understand that webpack main purpose is to bundle browser scripts that benefit greatly from reducing the size of the bundle. I’d still appreciate to be able to use webpack for bundling my node applications, because of it’s great ecosystem of plugins and documentation.
What I’ve been able to come up with is this config:
// ./webpack.config.js
import path from "path";
export default (env, argv) => {
return {
entry: "./src/index.js",
output: {
path: path.resolve("."),
filename: "index.js",
library: {
type: "module",
},
},
experiments: {
outputModule: true,
},
};
};
// ./src/index.js
export const add = (x, y) => {
return x + y;
};
Using library: { type: "module" }
(which requires experiments: { outputModule: true }
) at least outputs the “unused” exports to ./index.bundle.js
, but the output code – while working perfectly fine – looks terribly bloated and way more complicated than the original function declared in ./index.js
:
// ./index.bundle.js
var e = {
d: (r, o) => {
for (var t in o)
e.o(o, t) &&
!e.o(r, t) &&
Object.defineProperty(r, t, { enumerable: !0, get: o[t] });
},
o: (e, r) => Object.prototype.hasOwnProperty.call(e, r),
},
r = {};
e.d(r, { W: () => o });
const o = (e, r) => e + r;
var t = r.W;
export { t as add };
Am I missing out on something obvious here, or is this just the way, the output is expected to look? Or might webpack just be the wrong tool for the job altogether?
Thanks ind advance for any tips!
TimMKuehle is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.