The design of stacks of layered materials in which adjacent layers interact by van der Waals forces has enabled the combination of various two-dimensional crystals with different electrical, optical and mechanical properties as well as the emergence of novel physical phenomena and device functionality. Here, we report photoinduced doping in van der Waals heterostructures consisting of graphene and boron nitride layers. It enables flexible and repeatable writing and erasing of charge doping in graphene with visible light. We demonstrate that this photoinduced doping maintains the high carrier mobility of the graphene/boron nitride heterostructure, thus resembling the modulation doping technique used in semiconductor heterojunctions, and can be used to generate spatially varying doping profiles such as p-n junctions. We show that this photoinduced doping arises from microscopically coupled optical and electrical responses of graphene/boron nitride heterostructures, including optical excitation of defect transitions in boron nitride, electrical transport in graphene, and charge transfer between boron nitride and graphene.