Install fire/smoke alarm directly to stud or in electrical box?
A proper electrical box is the only way to do this. You CANNOT simply cut a hole and pass the wires through. Any and all line voltage (120/240V and up) splices must be in an approved box and be accessible, meaning you cannot bury a junction or splice box.
I could cite all sorts of relevant codes but I don't think that's necessary. This should be obvious.

Here is a recent thread on this very subject: What type of electrical box do I use for a hard-wired smoke detector?

Remember, it is almost a certainty (code wise in the US) that an AFCI breaker is required.