Over the last decade, a handful of the nation’s small energy companies pulled off a coup. Right under the noses of the industry’s biggest players, they discovered huge amounts of natural gas in fields stretching from Texas to Pennsylvania.

One of these companies, XTO Energy, grew almost unnoticed into the nation’s second-largest gas producer, amassing a substantial portfolio of gas fields, and developing expertise in the complex technology needed to extract the gas from beds of a dark rock called shale.

Now, the biggest energy companies are paying attention.

Exxon Mobil, the world’s largest publicly traded oil and gas producer, said Monday that it had agreed to buy XTO in an all-stock deal valued at $31 billion, the biggest oil and gas deal in four years.

The purchase allows Exxon to expand in shale gas, an area that has seen tremendous growth, and increase its gas resources by 45 trillion cubic feet, roughly equivalent to two years of domestic demand. The transaction is the company’s biggest since the $81 billion merger of Exxon and Mobil in 1999.