Since the Google Maps JS API is being loading as an external dependency — not a standard Node module — you need to tell Webpack that it is external and you can then use the providePlugin to provide it to all your scripts.
I don’t think you should really need to do the ProvidePlugin step I have above. That would only be if you wanted to provide google to all the scripts. Instead, I would just add import google from 'google' where I need it.
Now how would this work if the script is enqueued on only one page?
For example I only use the places API on the checkout page of woocommerce, for autocompletion.
This below is my exact problem. Played around with a few things and search quite a lot however i have no clue on how to make this work even with the function.
This does seem like something that would happen commonly?
You haven’t posted an error code, so it’s a little unclear what the problem is that you’re running into.
By default, Sage compiles all your javascript into a single file, and it does this using webpack. The issue Aitor was running into was that when webpack built that single JS file, it was unable to find the google library–because that library is enqueued by WordPress on the page when the site is visited, not included as part of build process. Adding google to externals tells webpack that when its building that single file, it doesn’t need to look for google because that library will be available when the script runs in the browser.
Sage also provides a system for routing JS scripts: there are examples that come with it. You can use this router to only import google on the routes where it’s actually needed.
Sorry if I was unclear, i’ll try to explain it with errors.
The idea:
i’m using the Google Maps API on the WooCommerce checkout page to autocomplete the address fields.
Current Situation:
Currently I enqueue the Google Maps script in ‘setup.php’ on all pages. With the following code. wp_enqueue_script('google-places', 'https://maps.googleapis.com/maps/api/js?v=3&libraries=places&key='.get_option( 'bull-api-keys-maps-key'), false, null ,false);
I also have a routed JS file on the checkout page. In which i do import google from 'google'; and the code that interacts with the api of course.
Then in webpack externals i have: google: 'google'
Wanted Outcome
Since i only use the Google Maps script on the checkout page, I only want to enqueue it there. Therefore I added in a check, to see if it is the checkout page ‘setup.php’ if(is_checkout()){ wp_enqueue_script('google-places', 'https://maps.googleapis.com/maps/api/js?v=3&libraries=places&key='.get_option( 'bull-api-keys-maps-key'), false, null ,false); }
Now this works fine on the checkout page, however on other pages i’m getting errors as the script is not included there. Uncaught Error: Cannot find module "google"
Now the question, how do we configure webpack correctly, so that it does not need 'google' to be available on every page?