javascript - Uncaught SyntaxError: Cannot use import statement outside a module Laravel + Alpine.js

one text

I am trying to add the following package to my Laravel project, in the hope that I can get it working. https://github.com/segmentio/analytics-next

I am a newbie and have done a lot of reading of possible solutions such as setting type="module" and making some changes to the script.

None of these work for my particular situation as the script isn't as simple as in those instructions.

I am trying to add the script in the head section of app.blade.php in my application.

If I just add the regular Segment snippet code there, it works fine.

<script>
  !function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","once","off","on","addSourceMiddleware","addIntegrationMiddleware","setAnonymousId","addDestinationMiddleware"];analytics.factory=function(e){return function(){var t=Array.prototype.slice.call(arguments);t.unshift(e);analytics.push(t);return analytics}};for(var e=0;e<analytics.methods.length;e++){var key=analytics.methods[e];analytics[key]=analytics.factory(key)}analytics.load=function(key,e){var t=document.createElement("script");t.type="text/javascript";t.async=!0;t.src="https://cdn.segment.com/analytics.js/v1/" + key + "/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(t,n);analytics._loadOptions=e};analytics._writeKey="<my-key>";;analytics.SNIPPET_VERSION="4.15.3";
  analytics.load("<my-key>");
  analytics.page();
  }}();
</script>

But if I remove that, and add the following code, I get the error from the title.

<script>
import { AnalyticsBrowser } from '@segment/analytics-next'

const analytics = AnalyticsBrowser.load({ writeKey: '<YOUR_WRITE_KEY>' })

analytics.identify('hello world')

document.body?.addEventListener('click', () => {
  analytics.track('document body clicked!')
})
</script>

Would someone be able to help me on the correct way of getting this loaded?

Thanks

Source