How to share js code between hubspot javascript module files

Hi,

I have a serie of hubspot modules that have javacript files that use the same logic. I would like to extract the common code to a js file and then import that code to be used on the diferent js module files so that I don’t have duplicate code across the modules.

How can I do this? Is it even possible?

Hi @sidcamara,
Thank you for reaching out to the Community!
I found these similar posts for you that might be of interest:
- Remove duplicate modules in JavaScript bundles
- Hubspot Website optimization

I also wanted to invite a couple of subject matter experts to this conversation @jonchim, @alyssamwilie and @stefen do you have suggestions to help @sidcamara, please?
If anybody else has anything to add and/or share, please feel free to join in the conversation :slightly_smiling_face:
Thanks and have a lovely day!
Best,
Bérangère

Thank you very much @BérangèreL for the support.
Have a great day and week. :wink:

@BérangèreL @sidcamara you can definitely do that. I’d recommend using ES Modules since that’s the modern standard and basically built for this exact purpose. You can use ES Modules in HubSpot by doing this:

{% require_js %}
<script type="module">
 import {sayHi} from 'https://example.com/file-manager/example.js';

 document.body.innerHTML = sayHi('John');
</script>
{% end_require_js %}

this way your “sayHi” function can be edited later on and anywhere it’s being imported will automatically get updated. ES6 modules for the win!
This is currently the only way to use ES6 modules in HubSpot since you cannot alter the `type` attribute via the other functions as of right now.

Hi @stefen.
Thank you very much for the reply and suggestion.
I think I understand why I can’t do exacly what I was thinking. The modules are bundled on the hubspot server and then the `module.js` files are imported as scripts on the client side. So the only way to share code is using the browser web api ES6 modules.

There is no way of doing it on the server side.
Something along these lines I would think.

Thanks for the time and effort on the support. :wink:

Have a great day.

Or, you can compile/bundle the files yourself before uploading to HubSpot.