We study the evolution of global shapes of galaxies using cosmological simulations. The shapes refer to the components of dark matter (DM), stars and gas at the stellar half-mass radius. Most galaxies undergo a characteristic compaction event into a blue nugget at z ∼ 2 − 4, which marks the transition from a DM-dominated central body to a self-gravitating baryonic core. We find that in the high-z, DM-dominated phase, the stellar and DM systems tend to be triaxial, preferentially prolate and mutually aligned. The elongation is supported by an anisotropic velocity dispersion that originates from the assembly of the galaxy along a dominant large-scale filament. We estimate that torques by the dominant halo are capable of inducing the elongation of the stellar system and its alignment with the halo. Then, in association with the transition to self-gravity, small-pericenter orbits puff up and the DM and stellar systems evolve into a more spherical and oblate configuration, aligned with the gas disc and associated with rotation. This transition typically occurs when the stellar mass is ∼ 10 9 M and the escape velocity in the core is ∼ 100 km s −1 , indicating that supernova feedback may be effective in keeping the core DM-dominated and the system prolate. The early elongated phase itself may be responsible for the compaction event, and the transition to the oblate phase may be associated with the subsequent quenching in the core.