ndparker / rjsmin

Fast javascript minifier for Python
http://opensource.perlig.de/rjsmin/
Apache License 2.0
60 stars 15 forks source link

Template literals not minified properly #18

Open 1oglop1 opened 4 years ago

1oglop1 commented 4 years ago

Hi, I found similar problem has been discussed in #8 and #16.

I'm fairly new to JS so please enlighten me if what am I reporting is a duplicate and why.

I have this test.js

window.location.origin = `${window.location.protocol}//${window.location.hostname}${window.location.port ? ':' + window.location.port : ''}`

which get's minified into

window.location.origin=`${window.location.protocol}//${window.location.hostname}${window.location.port ? ':' + window.location.port : ''}`

As you can see some parts were minified but the whitespace around ternary operator is preserved

expected output is:

window.location.origin=`${window.location.protocol}//${window.location.hostname}${window.location.port?":"+window.location.port:""}`;
ndparker commented 4 years ago

Right now you're seeing a hack in rjsmin. Since it's regex based it cannot easily handle nested template strings (or JS code inside template strings for that matter), so it treats them as "regular" strings. That way, they don't break per se, but as a tradeoff are not minified (inside) either.

Until I've found a better a solution, that's how it is, sorry.

1oglop1 commented 4 years ago

Thanks for the quick response, this is what I thought.

Do you think that this could help to build better regexes? https://github.com/VerbalExpressions/PythonVerbalExpressions

(PS I could not make rjsmin running by python -m rjsmin it just hung on python 3.6.9`)

ndparker commented 4 years ago

No. The problem is that it's recursive, which cannot be mapped to regular expressions at all. So I need a way out of this, kind of similar to what I do in rcssmin. The main idea would be to split up the code-to-be-minified and process it in pieces. Not sure if it will work out. However I still need some time to test that theory :-)

python -m rjsmin waits for stdin. may thatswhy? The usage would be, e.g.

$ python -mrjsmin <test.js
1oglop1 commented 4 years ago

I guess this could help with parsing https://github.com/Kronuz/esprima-python, I do not have much experience with it but it looks something like which can do the job.

Ad. waits for stdin,... I see it now, I interpreted the readme differently python -mrjsmin <script >minified and my dyslectic brain took the <script> as a placeholder instead of interpreting it as in/out redirection :), also the reason I'm so dependent on syntax highlighter.