Google maps JS API in sage 9

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?

Hopefully this is a bit more clear :wink:

2 Likes