evanw / esbuild

An extremely fast bundler for the web
https://esbuild.github.io/
MIT License
38.16k stars 1.15k forks source link

DCE doesn't remove unreferenced `new Regexp`. #3750

Open JeanMeche opened 6 months ago

JeanMeche commented 6 months ago

While inspecting my bundle output I just saw that an unreferenced regex wasn't removed by DCE. It looks like it only affects regex created by new RegExp(...).

Is there a reason for that ?

const regex1 = new RegExp('foo'); // KO
const regex2 = /foo/ // OK

Demo

evanw commented 6 months ago

This is because esbuild considers throwing an exception to be a side effect, and new RegExp can potentially throw an exception (such as new RegExp('[')). The string literal is not checked for whether it's a valid regular expression or not.