We examine the gains from globalization in the presence of firm heterogeneity and potential resource misallocation. We show theoretically that without distortions, bilateral and export liberalizations increase aggregate welfare and productivity, while import liberalization has ambiguous effects. Resource misallocation can either amplify, dampen or reverse the gains from trade. Using model-consistent measures and unique new data on 14 European countries and 20 industries in 1998-2011, we empirically establish that exogenous shocks to export demand and import competition both generate large aggregate productivity gains. Guided by theory, we provide evidence consistent with these effects operating through reallocations across firms in the presence of distortions: (i) Both export and import expansion increase average firm productivity, but the former also shifts activity towards more productive firms, while the latter acts in reverse; (ii) Both export and import exposure raise the productivity threshold for survival, but this cut-off is not a sufficient statistic for aggregate productivity; (iii) Efficient institutions, factor and product markets amplify the gains from import competition but dampen those from export access.