Like Pert suggested use another serial port. Do not use the rx/tx used for usb on the Mega.
For the ESP you have two options.
- Either use Software serial and use other pins on your ESP.
- Implement the 'Webupdater' sketch from the ESP8266 library in your code. This way you can upload new firmware through a webpage.