Two-dimensional layered semiconductors such as MoS₂ and WSe₂ have attracted considerable interest in recent times. Exploring the full potential of these layered materials requires precise spatial modulation of their chemical composition and electronic properties to create well-defined heterostructures. Here, we report the growth of compositionally modulated MoS₂-MoSe₂ and WS₂-WSe₂ lateral heterostructures by in situ modulation of the vapour-phase reactants during growth of these two-dimensional crystals. Raman and photoluminescence mapping studies demonstrate that the resulting heterostructure nanosheets exhibit clear structural and optical modulation. Transmission electron microscopy and elemental mapping studies reveal a single crystalline structure with opposite modulation of sulphur and selenium distributions across the heterostructure interface. Electrical transport studies demonstrate that the WSe₂-WS₂ heterojunctions form lateral p-n diodes and photodiodes, and can be used to create complementary inverters with high voltage gain. Our study is an important advance in the development of layered semiconductor heterostructures, an essential step towards achieving functional electronics and optoelectronics.