The study of the production of nuclei and antinuclei in pp collisions has proven to be a powerful tool to investigate the formation mechanism of loosely bound states in high-energy hadronic collisions. In this paper, the production of protons, deuterons and 3He and their charge conjugates at midrapidity is studied as a function of the charged-particle multiplicity in inelastic pp collisions at s=5.02 TeV using the ALICE detector. Within the uncertainties, the yields of nuclei in pp collisions at s=5.02 TeV are compatible with those in pp collisions at different energies and to those in p–Pb collisions when compared at similar multiplicities. The measurements are compared with the expectations of coalescence and Statistical Hadronisation Models. The results suggest a common formation mechanism behind the production of light nuclei in hadronic interactions and confirm that they do not depend on the collision energy but on the number of produced particles.