Importing NPM packges for use within WordPress plugin

[ad_1]

Hey all,

I’ve been trying to implement/import functions from a specific NPM package (@azure/web-pubsub**).**
From what I’ve read, I’d need to use a tool such as Webpack to bundle the package into a bundle.js file, which can then be used in my wp plugin using the wp\_enqueue\_script() function.

However, for some reason I can’t get it to work.

Steps I have taken:

1. Setup a webpack project folder
2. npm installed webpack and webpack-cli.
3. npm installed @ azure/web-pubsub.
4. created my .js file in src/ to import the pubsub library.
5. npx webpack at this point still caused a few error (certain fallback issues)
6. Fixed the fallback errors and created the webpubsub.bundle.js file.
7. uploaded the webpubsub.bundle.js file to my wordpress site / plugin folder.
8. enqueue the javascript file in my plugin.php file.
9. implement the WebPubSubServiceClient() function.

When loading my page, in my developer console, however, it generates the following error:

**File: jquery.min.js?ver=3.7.0:2**
*jQuery.Deferred exception: WebPubSubServiceClient is not defined ReferenceError: WebPubSubServiceClient is not defined.*

**File: jquery.min.js?ver=3.7.0:2**
*Uncaught ReferenceError: WebPubSubServiceClient is not defined.*
*at HTMLDocument.<anonymous> (ajax-script.js?ver=6.3.1:11:26)*
*at e (jquery.min.js?ver=3.7.0:2:26990)*
*at t (jquery.min.js?ver=3.7.0:2:27292)*

&#x200B;

This is my enqueue function in my .php file:

`function enqueue_webpubsub_script() {`

`wp_enqueue_script(‘webpubsub’, plugin_dir_url(__FILE__) . ‘js/webpubsub.bundle.js’, array(), ‘1.1.1’, true);`

`wp_enqueue_script(‘ajax-script’, plugin_dir_url(__FILE__) . ‘js/ajax-script.js’, array(‘webpubsub’), ‘1.0.0’, true);`

`}`

`add_action(‘wp_enqueue_scripts’, ‘enqueue_webpubsub_script’);`

I’m not much of a web developer, and kind of at a loss at the moment. Anyone who can point me in the right direction?

[ad_2]

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer