Importing packages to Shopify Hydrogen App causes error: "ReferenceError: require is not defined"

Why I am getting errors when attempting to import packages to use in my Shopify Hydrogen app. I created the app using “npm create @Shopify_77 [email removed] Some packages work correctly, and some give the error: “ReferenceError: require is not defined” in the terminal/console. For example, on one of my components:

import MailchimpSubscribe from 'react-mailchimp-subscribe';​

This causes the error. How can I import packages for my app correctly without these errors? Thanks.

Hello @pbal , the reason is that you’re using a “CJS” only module in a Hydrogen Vite project which now uses “ESM” by default, to fix that, you can refer to this video: https://www.youtube.com/watch?v=jmNuEEtwkD4
My personal solution for that is using dynamic import the Mailchimp library like this:

const MailchimpModule = await import('react-mailchimp-subscribe');​

Learn more about dynamic import here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import#import_a_module_for_its_side_effects_only

1 Like

Awesome. This is very helpful. Thank you!

1 Like