I have seen a lot people do it different ways. If you are building a ranged character you are probably taking sharpshooter, primarily for negating lcover (the +10 damage is nice but not as important as canceling cover). Here are a few methods
1. CBE: I never do this personally but a lot of people do at tables I play. This requires 2 feats to do effectively which means you are substantially behind other builds for several levels until these are online. With this they continue to use their crossbow in melee. Of all the options, this is the one I like least of all. They usually end up lagging behind at high levels once the party starts finding good magic weapons because magic hand crossbows are nearly unheard of and without that they are behind most other builds. They also can't make Opportunity attacks, so it really is a "if caught in melee" situation.
2. Versatile Dex Build: The way I do it is I build a versatile character that is effective in melee and at ranged. If I get caught in melee I either draw a Rapier or two light weapons. Usually if it is a primary ranged build I will take a silvered short sword as a melee weapon. A rapier is better in many cases, but the key is flexibility and wielding a short sword lets you go with 2 weapon fighting when you want to, and that is pretty nice if you dispatch one enemy and can fling a weapon at another with a bonus.
Running a high dex lets you flex to the situation - find a flaming whip or girdle of giant strength and you go to being primarily melee without losing much at all and still having a good ranged option as your new "backup".
3. Strength Build: A third option for a ranged build is to run strength and use darts and thrown weapon fighting. Darts are finesse so you can use strength with them, and they are ranged so they work with shapshooter. If you are a battlemaster you can use quick toss to make a sharpshooter attack as a bonus action without using the attack action, this is particularly effective if you are an Arcane Trickster or other caster multiclass. With a high strength you are good in melee with just about any weapon if caught in melee. The downside here is the same as getting CBE - if you build for ranged specifically with sharpshooter it ties you to darts as a weapon. It is better in that it only costs one feat and has a lot of flex options if you are caught in melee with Two-weapon fighting and lots of available weapons. It is range limited though.
4. Go high strength and high dex: Most martials are going to use either strength or dex as adump stat, but there are advantages to running high numbers in both. This lets you do it all and is particularly effective if you have access to a very high AC or spell slots for upcasting Armor of Agathys or False Life.