I've planning to mount some shelves using these IKEA Lerberg brackets
Should I mount them to the wall or the shelf first?
You may not have a choice if the shelf locks in by sliding forward. If that's the case, you mount to the shelf first and then hang it on the wall. Otherwise, the wall blocks you from installing the shelf. And even if it's not necessary, you may want to do it that way to get the shelf tight to the wall. Mount the brackets 1/8" or less from the back of the shelf, so the shelf touches the wall just before they do. Then, after hanging, when you tighten the screws on the wall, the shelf will get pulled tight without any gaps.
I would mount the shelf onto the two brackets then take the entire shelf and mount it to the wall, first screwing or nailing one side ONLY the top screw and then leveling the shelf then screwing in the second bracket ONLY top screw.
Once it is level screw in the other screws.
You can use a level if you have one BUT do not only use a level, step back and eyeball it, then affix it permanent to the wall. Using only a level will not ensure that the shelf is actually "level" in the room as it is highly unlikely that your room is perfectly level (i.e. the floor may not be 100% level ;) )