I recently installed a NPM Package, Masonry, to my WordPress project. I would like to use it, but I am not sure where I should add the script.
I was thinking of adding it via functions.php where I will enqueue it and find it in my node_modules folder using
get_template_directory_uri() . /node_modules/masonry-layout/dist/masonry.pkgd.min.js
But I feel there should be a simpler/better way.
I have bootstrap installed, and in my local js file, I have
require(‘bootstrap’);
I then have a webpack mix that takes mixes all the js files I have and adds it to my /dist
Is there a similar way to add it to my package without having to use functions.php enqueue it? I would love to only have one js script enqueued rather than having several one. (Unless you think that is bad practice).
Something similar to:
require(‘masonry’);
Additionally, please don’t try to persuade me to use the CDN instead.
Here is the package: https://www.npmjs.com/package/masonry-layout
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
There’s no single correct way, but I guess something approaching the normal way would be:
- Have a package.json file in your theme (or plugin).
- Install whatever packages you want with
npm install, which will install the package intonode_modules/inside your theme. - Inside your main script/entrypoint, include that script with
require()orimport. - 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' ] );
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0