I am building a components library which is pre-compiled using Rollup.
My components lib has hundreds of files, at random depths, and I need all files with specific name pattern (*.constants.js) to not be tree-shaken (legacy backward-compatibility with another project which consumes the one I am working on)
main.js (entry file)import { A } from 'foo';
console.log(A)
foo.jsexport const A = 1;
export const B = 1;
export const C = 1;
/build/foo.jsconst A = 1;
export { A };
A very important thing for me is to keep the ability of other codebases (which are using "my" components lib) to be able to import specific things from specific files, such as the above foo.js example
Question -
How do I keep the exports from being tree-shaken out of the output (only for *.constants.js in my real scenario)?
{
input: 'src/main.js',
output: {
dir: 'build',
format: 'es', // imperative
chunkFileNames: '[name].js',
entryFileNames: '[name].js',
preserveModules: true, // imperative
preserveModulesRoot: 'src', // imperative
sourcemap: true,
exports: 'named',
}
}
I ended up doing something ugly, but minimal, by tricking rollup to treat tree-shaken variables as if they are used, but dumping them on the global this variable, under a random namespace:
For the code example in the question, where only A is really used internally by my components, lib, if I want to keep the exports for B & C I do:
globalThis.__rollup_no_tree_shaking = {B, C};