Solved

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

pbal
Shopify Partner
4 0 4
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/hydrogen@latest". 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.
Accepted Solution (1)

Weaverse
Shopify Partner
73 23 32

This is an accepted solution.

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_f...

Helping merchants build super unique, high-performance storefronts using Weaverse + Hydrogen.
Looking for Development & Agency partners.
If you find the answer helpful, give it a thumbs up!
Our App: Theme Customizer for Shopify Hydrogen
Join our Weaverse + Hydrogen community: Weaverse Community

View solution in original post

Replies 2 (2)

Weaverse
Shopify Partner
73 23 32

This is an accepted solution.

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_f...

Helping merchants build super unique, high-performance storefronts using Weaverse + Hydrogen.
Looking for Development & Agency partners.
If you find the answer helpful, give it a thumbs up!
Our App: Theme Customizer for Shopify Hydrogen
Join our Weaverse + Hydrogen community: Weaverse Community
pbal
Shopify Partner
4 0 4

Awesome. This is very helpful. Thank you!