1

I'm trying to add dynamic import into my code to have a better performance on the client-side. So I have a webpack config where is bundling js files. On SFCC the bundled files are in the static folder where the path to that files is something like this: /en/v1569517927607/js/app.js)

I have a function where I'm using dynamic import of es6 to call a module when the user clicks on a button. The problem is that when we call for that module, the browser doesn't find it because the path is wrong.

/en/lazyLoad.js net::ERR_ABORTED 404 (Not Found)

This is normal because the file is on /en/v1569517927607/js/lazyLoad.js.

There is a way to get it from the right path? Here is my code.

window.onload = () => {
    const lazyAlertBtn = document.querySelector("#lazyLoad");

    lazyAlertBtn.addEventListener("click", () => {
        import(/* webpackChunkName: "lazyLoad" */ '../modules/lazyLoad').then(module => {
            module.lazyLoad();
        });
    });
};

3 Answers3

2

I had the same problem and solved it using the Merchant Tools > SEO > Dynamic Mapping module in Business Manager.

There you can use a rule like the following to redirect the request to the static folder:

**/*.bundle.js i s,,,,,/js/{0}.bundle.js

All my chunk files are named with the <module>.bundle pattern.

Here you can find more info :
https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/content/b2c_commerce/topics/search_engine_optimization/b2c_dynamic_mappings.html

Hope this helps.

sholsinger
  • 3,028
  • 2
  • 23
  • 40
Juan10
  • 21
  • 2
1

I believe you'll likely need to do some path.resolve() magic in either your import statement or your webpack.config.js file as is shown in the accepted answer to this question: Set correct path to lazy-load component using Webpack - ES6

sholsinger
  • 3,028
  • 2
  • 23
  • 40
1

We did it in a different way. That required two steps

  1. From within the template file add a script tag that creates a global variable for the static path. Something like
// inside .isml template
<script>
    // help webpack know about the path of js scripts -> used for lazy loading
    window.__staticPath__ = "${URLUtils.httpsStatic('/')}";
</script>
  1. Then you need to instruct webpack to know where to find chunks by changing __webpack_public_path__ at runtime
// somewhere in your main .js file
// eslint-disable-next-line
__webpack_public_path__ = window.__staticPath__ + 'js/';

Optional step:

You might also want to remove code version from your __staticPath__ using replace (at least we had to do that)

__webpack_public_path__ = window.__staticPath__.replace('{YOUR_CODE_VERSION_GOES_HERE}', '') + 'js/';

Dharman
  • 30,962
  • 25
  • 85
  • 135
bboydflo
  • 907
  • 1
  • 15
  • 24