AnYiEE / AwesomeGadgets

Storage, management, compilation, and automatic deployment of MediaWiki gadgets.
GNU General Public License v3.0
5 stars 5 forks source link

Allow behavior to differ between different wikis with env variables #30

Open Dianliang233 opened 1 month ago

Dianliang233 commented 1 month ago

It seems like that currently the only way to allow the scripts to behave differently across two wikis is to:

It would be preferable to have something like this:

if (import.meta.env.WIKI === 'awiki') {
  console.log('this is from awiki');
} else if (import.meta.env.WIKI === 'bwiki') {
  console.log('this is from bwiki');
}

Output before treeshake:

if (true) {
  console.log('this is from awiki');
} else if (false) {
  console.log('this is from bwiki');
}

Treeshaken:

// conditional removed
console.log('this is from awiki');
// unreachable code removed

This is, in fact, very easy to implement if we could allow esbuild to run once for each wiki. However this might cause performance issues depending on how much time each build takes and how many wikis are defined. I don't know if there would be any good alternatives though.

Similarly, with CSS, it might also be possible for us to define a custom CSS at-rule with PostCSS. However this might not be needed as it's very easy to override CSS.

AnYiEE commented 2 weeks ago

In fact, currently during compilation, Tree shaking is already enforced for esbuild (esbuild does not enable tree shaking for cjs format by default).

But just tested it, Tree shaking didn't actually take effect, but after passing minify: true to esbuild, tree shaking took effect. I'm not sure why, it seems that there is no mention of this in esbuild's documentation.

So, with tree shaking already enabled, simply append minify: true to esbuildOptions, and add a line similar to 'process.env.WIKI': '"awiki"' in the define object. Run the following code to see the effect you mentioned.

if (process.env.WIKI === 'awiki') {
    console.log('this is from awiki');
} else if (process.env.WIKI === 'bwiki') {
    console.log('this is from bwiki');
}

The reason for needing define is that the current usage of esbuild in the repo does not actually read environment variables.