Perhaps the same way virus did so... and before cellular organisms evolved. Remember there are many kinds of virus (single or double stranded DNA or RNA) This is a such a basic question as how the first polymeric organic molecules evolved; then surrounded by membranes, then... voila, we appeared. But be sure: a good start to find answers is to learn making the right questions. Yours is a very good one.
This is a good question and related to evolution of life. To solve this question that how plasmid evolved first we should see that how DNA evolved? The evolution of plasmids may based on the requirement of small circular DNA molecule which contains Ori C and replication machinery those can transmit from one organism to other organism through Horizontal Gene Transfer... for more detail you can visit below link ....