Imagine that the gas is confined in a cylindrical container fitted with a movable piston of area A. Suppose the gas is in equilibrium and its pressure is P. Then the forces acting on the piston must cancel. The gas exerts an outward force equal to F(gas)=PA. Then the external force must be F(ext)=-F(gas).
Imagine that the external force is just a bit smaller than the external force, so the gas expands, but the expansion is so slow that the kinetic energy of the piston is negligible. In this case the total work done on it is zero. The total work is equal to the work of the gas and the work of the external agent, and it is zero in a quasistatic expansion. dW=dW(gas)+dW(ext)=0
The work is displacement times force. When the gas expands, the force points outward and the piston moves outward by a small amount, dx. The work of the gas is positive W(gas)=F(gas)dx>0.
The total work is zero,
dW(gas)+dW(ext)=0
that means dW(external)=-dW(gas)..
This is logical as the external force points inward, while the piston displaces outward. Force is opposite to the displacement, so the external work is negative.
Now suppose that the force of the gas is just a bit smaller so the external force overcomes the force of the gas. Then the gas is compressed, the piston moves inward while the gas exerts an outward force on the piston. In this case, the work of the gas is negative. At the same time, the external work is positive, as the piston moves inward and the external force also points inward.
You can conclude that in case of quasystatic expansion or compression of the gas the work of the gas is opposite to the external work.
W(gas)=-W(external).
The force the gas exerts on the piston is F(gas)=PA, and the work done when the piston displaces by dx is dW=(PA)dx. Adx is the change of volume. So the work of the gas is dW(gas)=PdV, positive during expansion (dV>0) and negative during compression (dV<0).
ehild