I've been trying to learn how to write code that is tree shaking friendly, but have run into a problem with unavoidable side effects that I'm not sure how to deal with.
In one of my modules, I access the global Audio
constructor and use it to determine which audio files the browser can play (similar to how Modernizr does it). Whenever I try to tree shake my code, the Audio
element and all references to it do not get eliminated, even if I don't import the module in my file.
let audio = new Audio(); // or document.createElement('audio')
let canPlay = {
ogg: audio.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '');
mp3: audio.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '');
// ...
};
I understand that code that contains side effects cannot be eliminated, but what I can't find is how to deal with unavoidable side effects. I can't just not access a global object to create an audio
element needed to detect feature support. So how do I handle accessing global browser functions/objects (which I do a lot in this library) in a way that is tree shaking friendly and still allows me to eliminate the code?
let audio = () => new Audio()
thunk? – Birlaudio
function and set thecanPlay
themself? – Contravallationaudio
themselves to obtain theAudio
value, and then they would plug it intocanPlay
, which would have to be parametrized to accept anAudio
value. – Birl