How to properly add NPM packages and integrate them in WordPress?

There’s no single correct way, but I guess something approaching the normal way would be:

  1. Have a package.json file in your theme (or plugin).
  2. Install whatever packages you want with npm install, which will install the package into node_modules/ inside your theme.
  3. Inside your main script/entrypoint, include that script with require() or import.
  4. Configure your build process so that you have a single JS file that you can enqueue with WordPress from functions.php.

You’ll notice that pretty much none of this has anything to do with WordPress. The only thing you want for WordPress is to have your build process produce a single file that can be enqueued with wp_enqueue_script(), since you don’t want to have to enqueue a large number of files. How to do that is entirely dependent on the tools you’re using, and is unrelated to WordPress.

However, FWIW, WordPress already bundles the Masonry script, so you shouldn’t need to bundle it yourself at all. Just declare it as a dependency when enqueueing your script with wp_enqueue_script():

wp_enqueue_script( 'my-handle', '/path/to/my/script.js', [ 'masonry' ] );