Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid JS variable renaming in HTML files on ParcelJS

I am using ParcelJS as a module bundler and for some reasons I am using JS variables in the HTML which are later to be read by JS code.

In my HTML:

<script>
  var myVar = {
    key1: 'value1',
    key2: 'value2'
  };
</script>

In my JS:

console.log(window.myVar.key1);

When I build the static site with parcel build, the JS variable in the HTML gets renamed, so I can't read it from the JS file anymore:

<script>var a = { key1: 'value1', key2: 'value2' };</script>

According to the Parcel docs, it looks like the renaming (mangling) is done by htmlnano, which uses Terser under the hood for the JS minification.

I've tried using a .htmlnanorc file with the following contents:

{
  "minifyJs": {
    "mangle": false
  },
  "removeComments": false
}

I've only added the removeComments option just to make sure the .htmlnanorc file is being processed. HTML comments are kept, so it is.

But the JS variable keeps getting renamed, even though I've tried several Terser configurations according to their docs. So it looks like htmlnano is ignoring any configs under the minifyJs key.

Is there anything I am doing wrong? Or could it be some kind of ParcelJS or htmlnano bug?

like image 612
jorditarrida Avatar asked Oct 21 '25 09:10

jorditarrida


1 Answers

Change your variable names to

<script>
  window.myVar = {
    key1: 'value1',
    key2: 'value2'
  };
</script>

There's no option to change this behavior using parcel.js, so you have to go through a workaround.

Source

like image 148
Alexandre Elshobokshy Avatar answered Oct 23 '25 00:10

Alexandre Elshobokshy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!