Search code examples
jquerymagentoshopifyrequirejsconfig

How to solve Uncaught ReferenceError: require is not defined


Problem

I'm working on migrating my product information from Magento to Shopify, and one of the field is an entire HTML document. While the HTML and CSS can be correctly display, the jQuery codes in <script> tags do not work properly.

Here's a sample code in the HTML document:

var $thPic = ["https://some/path/to/images/001.png","https://some/path/to/images/002.png",
"https://some/path/to/images/003.png"];
var $thList = [];

for (i = 0; i < $thPic.length; i++) {
    $thList[i] = new Image();
        if (i === 1) {
            $thList[i].onload = function () {
                console.log('Done');
            };
        };
    $thList[i].src = $thPic[i];
}

require(['jquery','fancymedia' ], function ($) {
    $(document).ready(function() {
        $('.fancybox-media').fancybox({
            openEffect  : 'none',
            closeEffect : 'none',
            helpers : {
                media : {}
            }
        });
    });
});

I have a more than 1000 HTML documents for more than 1000 products, so it will be very time consuming if I need to rewrite all the functions. Could this be solved by including any libraries in the header, using any third party software, removing require(['xxxx','yyyy'], function ($) {}) wrapper, or adding other config or wrapper to existing code?

Solution Attempted

I have tried to include jQuery and Require.js library CDN in the header, but it still gives me error.

Here's one of the error messages that I got:

GET https://shop-name.myshopify.com/products/owlcarousel.js net::ERR_ABORTED 404

Uncaught Error: Script error for "owlcarousel"
https://requirejs.org/docs/errors.html#scripterror
    at makeError (require.min.js:1:1795)
    at HTMLScriptElement.onScriptError (require.min.js:1:17084)

I was trying to configure the require.js so it looks for the JS files in the correct location, but I have no clues if this could fix the problem that I have:

<script>
  require.config({
    baseUrl: 'https://cdn.shopify.com/s/files/.../assets/js',
    paths: {
      jquery: 'jquery.min',
      owlcarousel: 'owl.carousel.min'
    }
  });
</script>

It would be great if anyone could let me know what goes wrong here, and it would be awesome if anyone could tell me how to fix this!

Any input is appreciated!


Solution

  • You upload your JS to Assets in Shopify. That then lets you reference them in your code. You can assure yourself that no matter what you did in Magento, there exists an equivalent in Shopify. I think once you carefully and closely examine how Shopify templates render, you'll quickly drop Magento and wonder how you lasted so long with that clunker.