<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rahul Jain on Medium]]></title>
        <description><![CDATA[Stories by Rahul Jain on Medium]]></description>
        <link>https://medium.com/@rahul.jain373?source=rss-21172633760a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vZ7XooOoKSoUbQl1zzJrvg.jpeg</url>
            <title>Stories by Rahul Jain on Medium</title>
            <link>https://medium.com/@rahul.jain373?source=rss-21172633760a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 10:31:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rahul.jain373/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Stop Loading All Locale Strings: A Step-by-Step Guide to Reducing Bundle Size with Webpack]]></title>
            <link>https://medium.com/adobetech/stop-loading-all-locale-strings-a-step-by-step-guide-to-reducing-bundle-size-with-webpack-d052dece4693?source=rss-21172633760a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d052dece4693</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[adobe-engineering]]></category>
            <category><![CDATA[front-end-web-development]]></category>
            <category><![CDATA[localization]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Rahul Jain]]></dc:creator>
            <pubDate>Thu, 29 Jun 2023 09:42:39 GMT</pubDate>
            <atom:updated>2023-08-03T05:58:48.889Z</atom:updated>
            <content:encoded><![CDATA[<h4>Co-author: <a href="https://medium.com/@imamudin">Imamudin Naseem</a>.</h4><h4>Looking to reduce content load time? Here’s how to optimize the size of your bundle to avoid slowing down your application.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*nWfIXsKvGqX70vqhvaC0Qw.jpeg" /></figure><p>Welcome to the <strong>first article in our series</strong> on localization bundling optimization. In this series, we delve into essential techniques to enhance the performance and reduce the bundle size of your web applications through effective localization strategies.</p><p>In modern web development, optimizing bundle size is crucial for improving application performance and user experience. One common issue that front-end developers face is <strong>including all locale strings</strong> in the application bundle, which can significantly increase the bundle size and slow down the application.</p><p>In this first article, we will discuss how to optimize bundle size by relocating <strong>locale files to separate chunks</strong> and loading only the <strong>user-specific locale chunk</strong>. This approach can help developers working on front-end applications to reduce the application content load time. This is applicable across Adobe products such as AEP, AJO, Adobe Campaign, Analytics, and so on.</p><p>Like application code, vendor packages can also contain locale-specific strings, and including all these strings in the application bundle can significantly impact its size. The <strong>second article</strong> in the series will provide a build strategy for packages so that consuming applications can avoid loading all languages’ strings at once and load only the desired one.</p><p>You can read the second article here: <a href="https://blog.developer.adobe.com/split-javascript-packages-chunk-based-on-locale-a-step-by-step-guide-1a98700d65e0">Split Javascript Packages’ Chunk Based on Locale: A Step-by-Step Guide</a></p><blockquote><em>Examples referred in the article are collated here:</em></blockquote><blockquote><em>Github Repo: </em><a href="https://github.com/rahuljain936/locale-optimize">https://github.com/rahuljain936/locale-optimize</a></blockquote><blockquote>We used react and webpack in the examples, and they can be adapted for other web frameworks like vue, etc.</blockquote><h3>Optimizing bundle size</h3><p>Optimizing bundle size is vital for front-end applications because it reduces the amount of data that needs to be downloaded by the user’s browser.</p><p>One way to optimize bundle size is to separate locale files from the main bundle and load only the required ones when needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*UoXhWwgukysxPRxl1hhDOA.gif" /><figcaption>Single bundle Demo</figcaption></figure><p>To do this, we can use two approaches:</p><ul><li>High order component(HOC) with Dynamic expressions in import</li><li>Component-level dynamic expressions in import</li></ul><p>We’ll be using webpack for module bundling. Here are a few Key Features used:</p><ol><li><a href="https://webpack.js.org/api/module-methods/#dynamic-expressions-in-import"><strong>Dynamic Expressions in Import</strong></a>: The import() function with dynamic expressions allows for the dynamic loading of language files based on the user&#39;s locale.</li><li><a href="https://webpack.js.org/api/module-methods/#magic-comments"><strong>Placeholders in Webpack Name</strong></a>: The webpackChunkName placeholder, specified as [request], dynamically assigns a chunk name based on the imported module. This ensures one chunk is created for each locale across components, facilitating code splitting and lazy loading of translations.</li></ol><h3>HOC with dynamic expressions in import</h3><blockquote><a href="https://github.com/rahuljain936/locale-optimize/tree/main/demo02-dynExprImport">Example: Check code in github</a></blockquote><p>By leveraging this feature, you can optimize localization bundles by dynamically importing only the required language files based on the user’s locale.</p><p>Using dynamic expressions in import involves dynamically constructing the import path based on the selected locale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*pdYcNALdCDYbX6z10neltw.gif" /><figcaption>Optimized localization bundling demo</figcaption></figure><p>In the provided code, the ‘LocalizationHoc’ is a high-order component to implement dynamic expressions in import for loading specific locale strings. It takes a ‘Component’ and ‘path’ as parameters and returns a localized component.</p><pre>// Localization high order component<br><br>function loadMessages(path, locale) {<br>  switch (locale) {<br>    case &quot;es&quot;:<br>      return import(<br>        /* webpackChunkName: &quot;localeEs&quot; */<br>        /* webpackMode: &quot;lazy-once&quot; */<br>        `./components/${path}/lang/es.json`);<br>    default:<br>      return import(<br>        /* webpackChunkName: &quot;localeEn&quot; */<br>        /* webpackMode: &quot;lazy-once&quot; */<br>        `./components/${path}/lang/en.json`);<br>  }<br>}<br><br>function LocalizationHoc(Component, path) {<br>  return function LocalizedComp() {<br>    const intl = useIntl();<br>    const [messages, setMessages] = useState(null);<br>    useEffect(() =&gt; {loadMessages(path, intl.locale).then(setMessages)}, [intl.locale]);<br><br>    return messages ? (<br>      &lt;IntlProvider messages={messages}&gt;<br>        &lt;Component/&gt;<br>      &lt;/IntlProvider&gt;<br>    ) : null;<br>  }<br>}</pre><p>The ‘loadMessages’ function is responsible for dynamically importing the language files based on the specified ‘path’ and ‘locale’. It constructs the import path using template literals and uses webpack annotations to optimize the bundle splitting.</p><p><strong>lazy-once</strong> webpack mode is used to generate a single lazy-loadable chunk across multiple components that can satisfy all calls to import() for one locale.</p><pre>// Component using high order component wrapped localized component<br><br>function MyComponent() {<br> // …<br>}<br>// Create a localized version of MyComponent<br>const LocalizedComponent = LocalizationHoc(MyComponent, &quot;my-component&quot;);<br>// Usage in the application<br>function App() {<br> return (<br> &lt;div&gt;<br>   &lt;h1&gt;My App&lt;/h1&gt;<br>   &lt;LocalizedComponent /&gt;<br> &lt;/div&gt;<br> );<br>}</pre><p>Hence, the ‘LocalizedComponent’ is created using the ‘LocalizationHoc’ higher-order component. The ‘path’ parameter specifies the location of the language files for the component, and the appropriate language file is loaded based on the user’s locale.</p><blockquote>Advantages of Using Dynamic Expressions in Import:</blockquote><ul><li><strong>Code Reusability</strong>: With a single wrapper component, you can encapsulate the localization logic in one place. This promotes code reusability as the same wrapper component can be utilized across multiple components, reducing duplication and ensuring consistent localization implementation.</li><li><strong>Simplified Maintenance</strong>: Having a single wrapper component makes maintenance and updates more straightforward. If there are changes or additions to the localization files, you only need to modify the wrapper component rather than make changes in each individual component. This centralization simplifies the management of translations.</li></ul><blockquote>Disadvantages of Using Dynamic Expressions in Import:</blockquote><ul><li><strong>Increased Complexity</strong>: Implementing dynamic expressions in import introduces additional complexity to the codebase. Developers need to carefully manage the import paths and ensure they are constructed correctly based on the locale. This complexity can make the code harder to maintain and debug.</li><li><strong>Build-Time Dependency Analysis</strong>: Some build tools, like webpack, analyze dependencies at build time to generate the required bundles. Dynamic expressions in import can make it harder for these tools to analyze dependencies accurately, potentially leading to suboptimal bundle splitting.</li></ul><h3>Component-level dynamic expressions in import</h3><blockquote><a href="https://github.com/rahuljain936/locale-optimize/tree/main/demo03-dynImportCompLevel">Example: Check code in github</a></blockquote><p>Using dynamic expressions in import, along with placeholders in webpack names, you can dynamically construct the import path for the locale-specific language file within the component itself based on the user’s locale.</p><p>This enables efficient loading of translations specific to each component, reducing bundle size and improving performance.</p><p>In the provided code, the ‘ComponentLocalizationWrapper’ component demonstrates how to implement component-level dynamic import for loading user-specific locale strings. It uses dynamicimport()with a dynamic expression and webpack annotations to load the language file at runtime.</p><p>The webpackChunkName placeholder [request] dynamically assigns a chunk name based on the imported module, ensuring separate chunks for each language file.</p><pre>// Component<br><br>export default function ComponentLocalizationWrapper() {<br>  const {locale} = useIntl();<br>  const [messages, setMessages] = useState(null);<br>  useEffect(() =&gt; {<br>    import(/* webpackChunkName: &quot;[request]&quot; */`./lang/${locale}.json`)<br>    .then(setMessages) <br>  }, [locale]);<br><br>  return messages ? (<br>    &lt;IntlProvider messages={messages}&gt;<br>      &lt;Component/&gt;<br>    &lt;/IntlProvider&gt;<br>  ) : null;<br>}<br><br>function Component() {<br>  const {formatMessage} = useIntl();<br>  return (<br>    &lt;div&gt;<br>      &lt;div style={{ padding: 20 }} data-testid=&quot;examples&quot;&gt;<br>        {formatMessage({ id: &quot;message.argument&quot; }, { name: &quot;Rahul&quot; })}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>The component to be localized retrieves the translated messages from the loaded localization file and displays them accordingly.</p><blockquote>Advantages of Using Component-level Dynamic Import:</blockquote><p><strong>Granular Localization</strong>: Component-level dynamic import enables granular localization, allowing each component to load its specific localization file.</p><p>This approach offers fine-grained control over translations and allows for more targeted localization efforts. Instead of loading a single large translation bundle for the entire application, this approach enables individual components to import only the translations they require, resulting in more efficient and optimized localization.</p><blockquote>Disadvantages of Using Component-level Dynamic Import:</blockquote><p><strong>Code Duplication</strong>: With component-level dynamic import, there may be some duplication of code related to dynamic imports across multiple components. This can make the codebase more complex and harder to maintain.</p><h3>Conclusion</h3><p>In this blog post, we explored the challenges of bundling all locale strings in a front-end application and discussed strategies for optimizing bundle size.</p><p>By efficiently managing translations, we can improve application performance and provide a better user experience.</p><p>We examined two powerful techniques for optimizing bundle size: HOC with dynamic expressions in import and component level dynamic import.</p><p><strong>HOC with Dynamic expressions in import</strong> allows us to load specific locale strings based on the user’s preferred language. We explored the benefits of this approach, including code reusability, simplified maintenance, and consistent user experiences. However, it’s important to be mindful of the increased number of requests and complexity in dependency management that may arise.</p><p><strong>Component-level dynamic expression in import </strong>takes granular localization to the next level. Each component can load its specific localization file with granular control. It’s crucial to consider the potential drawbacks, such as the complexity of managing duplicate code and the impact on network requests.</p><blockquote>We used the <strong>HOC with dynamic expression in import</strong> approach for <strong>Adobe Campaign WebUI</strong> and <strong>Adobe Journey Optimizer reporting UI</strong> and achieved a significant <strong>30% reduction</strong> in the application package bundle load. This decision was based on a thorough analysis that took into account the following factors:</blockquote><ul><li><strong>Build-time Dependency Analysis:</strong> The higher-order component (HOC) was developed with careful consideration of its implications on bundle optimization and was able to effectively split the bundles, resulting in smaller and more efficient packages.</li><li><strong>Reduced Implementation Complexity:</strong> We ensured that the process of setting up and configuring the dynamic expression in import approach was well-defined and straightforward. This helped minimize the complexity involved in implementing this optimization technique, making it easier to maintain and debug the codebase.</li><li><strong>Large Codebase and Lerna Packages:</strong> Adobe Campaign WebUI consists of a substantial codebase distributed across multiple lerna packages. In this scenario, using component-level imports would have resulted in excessive code duplication.</li></ul><p>In conclusion, by following best practices and continually refining our approach, we can create high-performing applications that cater to users’ language preferences while delivering exceptional user experiences.</p><h3>Useful Links</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import">Dynamic import</a></li><li><a href="https://webpack.js.org/api/module-methods/#dynamic-expressions-in-import">Dynamic expressions in import</a></li><li><a href="https://webpack.js.org/api/module-methods/#magic-comments">WebpackChunkName with placeholders</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d052dece4693" width="1" height="1" alt=""><hr><p><a href="https://medium.com/adobetech/stop-loading-all-locale-strings-a-step-by-step-guide-to-reducing-bundle-size-with-webpack-d052dece4693">Stop Loading All Locale Strings: A Step-by-Step Guide to Reducing Bundle Size with Webpack</a> was originally published in <a href="https://medium.com/adobetech">Adobe Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop loading All Locale Strings: A Step-by-Step Guide to Reducing Bundle Size with Webpack]]></title>
            <link>https://medium.com/@rahul.jain373/stop-loading-all-locale-strings-a-step-by-step-guide-to-reducing-bundle-size-with-webpack-97730baf2164?source=rss-21172633760a------2</link>
            <guid isPermaLink="false">https://medium.com/p/97730baf2164</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[localization]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[bundling]]></category>
            <dc:creator><![CDATA[Rahul Jain]]></dc:creator>
            <pubDate>Mon, 05 Jun 2023 16:44:24 GMT</pubDate>
            <atom:updated>2023-06-05T16:44:24.464Z</atom:updated>
            <content:encoded><![CDATA[<h4>Optimizing Localization Bundling</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*HTES_h-z6GoaYfq8AaTs2Q.png" /></figure><p>Co-author: <a href="https://medium.com/@imamudin">Imamudin Naseem</a></p><p>In modern web development, optimizing bundle size is crucial for improving application performance and user experience. One common issue that frontend developers face is <strong>including all locale strings</strong> in the application bundle, which can significantly increase the bundle size and slow down the application. In this blog, we will discuss how to optimize bundle size by relocating <strong>locale files to separate chunks</strong> and loading only the <strong>user-specific locale chunk</strong>.</p><blockquote><em>Examples referred in the article are collated here:</em></blockquote><blockquote><em>Github Repo: </em><a href="https://github.com/rahuljain936/locale-optimize">https://github.com/rahuljain936/locale-optimize</a></blockquote><h3>Optimizing bundle size</h3><p>Optimizing bundle size is vital for front-end applications because it reduces the amount of data that needs to be downloaded by the user’s browser. One way to optimize bundle size is to separate locale files from the main bundle and load only the required ones when needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*UoXhWwgukysxPRxl1hhDOA.gif" /><figcaption>Single bundle Demo</figcaption></figure><p>To address this issue, we can use two approaches:</p><ul><li>High order component(HOC) with Dynamic expressions in import</li><li>Component-level dynamic expressions in import</li></ul><p>We’ll be using webpack for module bundling and here are a few Key Features used:</p><ol><li><a href="https://webpack.js.org/api/module-methods/#dynamic-expressions-in-import"><strong>Dynamic Expressions in Import</strong></a>: The import() function with dynamic expressions allows for the dynamic loading of language files based on the user&#39;s locale.</li><li><a href="https://webpack.js.org/api/module-methods/#magic-comments"><strong>Placeholders in Webpack Name</strong></a>: The webpackChunkName placeholder, specified as [request], dynamically assigns a chunk name based on the imported module. This ensures one chunk is created for each locale across components, facilitating code splitting and lazy loading of translations.</li></ol><h3>HOC with Dynamic expressions in import</h3><blockquote><a href="https://github.com/rahuljain936/locale-optimize/tree/main/demo02-dynExprImport">Example: Check code in github</a></blockquote><p>By leveraging this feature, you can optimize localization bundles by dynamically importing only the required language files based on the user’s locale. Using dynamic expressions in import involves dynamically constructing the import path based on the selected locale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*pdYcNALdCDYbX6z10neltw.gif" /><figcaption>Optimized localization bundling demo</figcaption></figure><p>In the provided code, the `LocalizationHoc` is a high-order component to implement dynamic expressions in import for loading specific locale strings. It takes a `Component` and `path` as parameters and returns a localized component.</p><pre>// Localization high order component</pre><pre>function loadMessages(path, locale) {<br>  switch (locale) {<br>    case &quot;es&quot;:<br>      return import(<br>        /* webpackChunkName: &quot;localeEs&quot; */<br>        /* webpackMode: &quot;lazy-once&quot; */<br>        `./components/${path}/lang/es.json`);<br>    default:<br>      return import(<br>        /* webpackChunkName: &quot;localeEn&quot; */<br>        /* webpackMode: &quot;lazy-once&quot; */<br>        `./components/${path}/lang/en.json`);<br>  }<br>}</pre><pre>function LocalizationHoc(Component, path) {<br>  return function LocalizedComp() {<br>    const intl = useIntl();<br>    const [messages, setMessages] = useState(null);<br>    useEffect(() =&gt; {loadMessages(path, intl.locale).then(setMessages)}, [intl.locale]);</pre><pre>    return messages ? (<br>      &lt;IntlProvider messages={messages}&gt;<br>        &lt;Component/&gt;<br>      &lt;/IntlProvider&gt;<br>    ) : null;<br>  }<br>}</pre><p>The `loadMessages` function is responsible for dynamically importing the language files based on the specified `path` and `locale`. It constructs the import path using template literals and uses webpack annotations to optimize the bundle splitting. <strong>lazy-once</strong> webpack mode is used to generate a single lazy-loadable chunk across multiple components that can satisfy all calls to import() for one locale.</p><pre>// Component using high order component wrapped localized component</pre><pre>function MyComponent() {<br> // …<br>}<br>// Create a localized version of MyComponent<br>const LocalizedComponent = LocalizationHoc(MyComponent, &quot;my-component&quot;);<br>// Usage in the application<br>function App() {<br> return (<br> &lt;div&gt;<br>   &lt;h1&gt;My App&lt;/h1&gt;<br>   &lt;LocalizedComponent /&gt;<br> &lt;/div&gt;<br> );<br>}</pre><p>Hence, the `LocalizedComponent` is created using the `LocalizationHoc` higher-order component. The `path` parameter specifies the location of the language files for the component, and the appropriate language file is loaded based on the user’s locale.</p><blockquote>Advantages of Using Dynamic Expressions in Import:</blockquote><ul><li><strong>Code Reusability</strong>: With a single wrapper component, you can encapsulate the localization logic in one place. This promotes code reusability as the same wrapper component can be utilized across multiple components, reducing duplication and ensuring consistent localization implementation.</li><li><strong>Simplified Maintenance</strong>: Having a single wrapper component makes maintenance and updates more straightforward. If there are changes or additions to the localization files, you only need to modify the wrapper component rather than make changes in each individual component. This centralization simplifies the management of translations.</li></ul><blockquote>Disadvantages of Using Dynamic Expressions in Import:</blockquote><ul><li><strong>Increased Complexity</strong>: Implementing dynamic expressions in import introduces additional complexity to the codebase. Developers need to carefully manage the import paths and ensure they are constructed correctly based on the locale. This complexity can make the code harder to maintain and debug.</li><li><strong>Build-Time Dependency Analysis</strong>: Some build tools, like webpack, analyze dependencies at build time to generate the required bundles. Dynamic expressions in import can make it harder for these tools to analyze dependencies accurately, potentially leading to suboptimal bundle splitting.</li></ul><h3>Component-level dynamic expressions in import</h3><blockquote><a href="https://github.com/rahuljain936/locale-optimize/tree/main/demo03-dynImportCompLevel">Example: Check code in github</a></blockquote><p>Using dynamic expressions in import, along with placeholders in webpack names, you can dynamically construct the import path for the locale-specific language file within the component itself based on the user’s locale. This enables efficient loading of translations specific to each component, reducing bundle size and improving performance.</p><p>In the provided code, the `ComponentLocalizationWrapper` component demonstrates how to implement component-level dynamic import for loading user-specific locale strings. It uses dynamicimport()with a dynamic expression and webpack annotations to load the language file at runtime. The webpackChunkName placeholder [request] dynamically assigns a chunk name based on the imported module, ensuring separate chunks for each language file.</p><pre>// Component</pre><pre>export default function ComponentLocalizationWrapper() {<br>  const {locale} = useIntl();<br>  const [messages, setMessages] = useState(null);<br>  useEffect(() =&gt; {<br>    import(/* webpackChunkName: &quot;[request]&quot; */`./lang/${locale}.json`)<br>    .then(setMessages) <br>  }, [locale]);</pre><pre>  return messages ? (<br>    &lt;IntlProvider messages={messages}&gt;<br>      &lt;Component/&gt;<br>    &lt;/IntlProvider&gt;<br>  ) : null;<br>}</pre><pre>function Component() {<br>  const {formatMessage} = useIntl();<br>  return (<br>    &lt;div&gt;<br>      &lt;div style={{ padding: 20 }} data-testid=&quot;examples&quot;&gt;<br>        {formatMessage({ id: &quot;message.argument&quot; }, { name: &quot;Rahul&quot; })}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>Component to be localized retrieves the translated messages from the loaded localization file and displays them accordingly.</p><blockquote>Advantages of Using Component-level Dynamic Import:</blockquote><p><strong>Granular Localization</strong>: Component-level dynamic import enables granular localization, allowing each component to load its specific localization file. This approach offers fine-grained control over translations and allows for more targeted localization efforts. Instead of loading a single large translation bundle for the entire application, this approach enables individual components to import only the translations they require, resulting in more efficient and optimized localization.</p><blockquote>Disadvantages of Using Component-level Dynamic Import:</blockquote><p><strong>Code Duplication</strong>: With component-level dynamic import, there may be some duplication of code related to dynamic imports across multiple components. This can make the codebase more complex and harder to maintain.</p><h3>Conclusion</h3><p>In this blog post, we explored the challenges of bundling all locale strings in a front-end application and discussed strategies for optimizing bundle size. By efficiently managing translations, we can improve application performance and provide a better user experience.</p><p>We examined two powerful techniques for optimizing bundle size: HOC with dynamic expressions in import and component level dynamic import.</p><p><strong>HOC with Dynamic expressions in import</strong> allows us to load specific locale strings based on the user’s preferred language. We explored the benefits of this approach, including code reusability, simplified maintenance, and consistent user experiences. However, it’s important to be mindful of the increased number of requests and complexity in dependency management that may arise.</p><p><strong>Component-level dynamic expression in import </strong>takes granular localization to the next level. Each component can load its specific localization file with granular control. It’s crucial to consider the potential drawbacks, such as the complexity of managing duplicate code and the impact on network requests.</p><blockquote>We used the <strong>HOC with dynamic expression in import</strong> approach for <strong>Adobe Campaign WebUI</strong> and <strong>Adobe Journey Optimizer reporting UI</strong> and achieved a significant <strong>30% reduction</strong> in the application package bundle load. This decision was based on a thorough analysis that took into account the following factors:</blockquote><ul><li>Build-time Dependency Analysis: The higher-order component (HOC) was developed with careful consideration of its implications on bundle optimization and was able to effectively split the bundles, resulting in smaller and more efficient packages.</li><li>Reduced Implementation Complexity: We ensured that the process of setting up and configuring the dynamic expression in import approach was well-defined and straightforward. This helped minimize the complexity involved in implementing this optimization technique, making it easier to maintain and debug the codebase.</li><li>Large Codebase and Lerna Packages: Adobe Campaign WebUI consists of a substantial codebase distributed across multiple lerna packages. In this scenario, using component-level imports would have resulted in excessive code duplication.</li></ul><p>In conclusion, these approaches can help developers working on frontend applications reduce the content load time as mentioned in the results above and this is applicable across DX products such as AEP, AJO, Adobe Campaign, Analytics etc. Hence by following best practices and continually refining our approach, we can create high-performing applications that cater to users’ language preferences while delivering exceptional user experiences.</p><h3>Useful Links</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import">Dynamic import</a></li><li><a href="https://webpack.js.org/api/module-methods/#dynamic-expressions-in-import">Dynamic expressions in import</a></li><li><a href="https://webpack.js.org/api/module-methods/#magic-comments">WebpackChunkName with placeholders</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97730baf2164" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering JS Modules: Seamlessly integrate multiple modules together]]></title>
            <link>https://medium.com/@rahul.jain373/mastering-js-modules-seamlessly-integrate-multiple-modules-together-37029d57c6ce?source=rss-21172633760a------2</link>
            <guid isPermaLink="false">https://medium.com/p/37029d57c6ce</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[es6-module]]></category>
            <category><![CDATA[commonjs]]></category>
            <category><![CDATA[js-module]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Rahul Jain]]></dc:creator>
            <pubDate>Fri, 05 May 2023 14:48:40 GMT</pubDate>
            <atom:updated>2023-05-09T04:58:08.406Z</atom:updated>
            <content:encoded><![CDATA[<h4>CommonJS and ES6 Modules</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*7jqEVg3H6rYt6eBIn8ArbA.png" /></figure><p>We will explore the CommonJS and ES modules and their usage in Node.js and the browser. We will also discuss how to use these modules in the front end with Webpack, and how to integrate <strong>CommonJS modules inside ES modules</strong>.</p><blockquote>Examples referred in the article are collated here:</blockquote><blockquote>⚡️ Stackblitz: <a href="https://stackblitz.com/edit/github-nofjl9-czkj4a">https://stackblitz.com/edit/github-nofjl9-czkj4a</a></blockquote><blockquote>Github Repo: <a href="https://github.com/rahuljain936/JS-modules">https://github.com/rahuljain936/JS-modules</a></blockquote><p>There are two main types of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules">JavaScript modules</a>: CommonJS and ES6. CommonJS modules are the traditional module format used in Node.js, while ES6 modules are a newer module format introduced in ECMAScript6.</p><h3>CommonJS Modules</h3><blockquote>⚡️ <a href="https://stackblitz.com/edit/github-nofjl9-czkj4a?file=demo01-cjs/package.json">Check Stackblitz for live demo</a></blockquote><p>CommonJS modules are a module format that is used primarily in Node.js. Here’s an example of a CommonJS module and its usage:</p><pre>// myModule.cjs<br>function myFunction() {<br>  console.log(&quot;CommonJS module Demo&quot;);<br>}<br>module.exports = myFunction;<br><br>// index.js<br>const myFunction = require(&quot;./myModule.cjs&quot;);<br>myFunction(); // logs &quot;CommonJS module Demo&quot;</pre><p>While CommonJS modules work well in Node.js, they have some limitations when used in the browser. One of the primary limitations is that CommonJS modules are loaded synchronously, which can block the execution of other scripts on the page.</p><h3>ES Modules</h3><blockquote>⚡️ <a href="https://stackblitz.com/edit/github-nofjl9-czkj4a?file=demo02-ES6/package.json">Check Stackblitz for live demo</a></blockquote><p>ES modules (ECMAScript modules) are a newer module format that is supported by all modern web browsers and Node.js. Here’s an example of an ES module and it’s usage:</p><pre>// myModule.mjs<br>export function myFunction() {<br>  console.log(&quot;ES6 Module Demo&quot;);<br>}<br><br>// index.js<br>import { myFunction } from &quot;./myModule.mjs&quot;;<br>myFunction();</pre><p>ES modules have some advantages over CommonJS modules. One of the primary advantages is that ES modules are loaded asynchronously by default, which allows other scripts on the page to continue executing while the module is being loaded.</p><p>However, ES modules are not supported by some of the legacy browsers and to ensure cross-browser compatibility, you may need to use a module bundler such as Webpack or Rollup.</p><blockquote>Check ES6 modules <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#browser_compatibility">Browser Compatibility chart</a> for more info.</blockquote><h3>Using ES Modules with Webpack</h3><p>To use ES modules with Webpack, you need to use import and export keywords in your JavaScript code. However, since not all legacy browsers support ES modules natively, you also need to use a Webpack plugin called babel-loader to transpile your ES modules to JavaScript that can be understood by all browser versions.</p><pre>// webpack.config.js<br>module.exports = {<br>  entry: &#39;./src/index.js&#39;,<br>  output: {<br>    filename: &#39;bundle.js&#39;,<br>    path: __dirname + &#39;/dist&#39;<br>  },<br>  module: {<br>    rules: [<br>      {<br>        test: /\.js$/,<br>        exclude: /node_modules/,<br>        use: {<br>          loader: &#39;babel-loader&#39;,<br>          options: {<br>            presets: [&#39;@babel/preset-env&#39;]<br>          }<br>        }<br>      }<br>    ]<br>  }<br>};</pre><p>In the above example, we have added a new module property to our Webpack configuration file that defines a rules array. The rules array specifies that any JavaScript files ending with .js should be transpiled using the babel-loader plugin, excluding the node_modules directory. The @babel/preset-env preset is used to transpile the ES modules to JavaScript that can be understood by all browser versions.</p><h3>Using CommonJS Modules Inside ES Modules</h3><p>JavaScript developers may find themselves in a situation where they need to use a CommonJS module inside an ES module. While this is not the recommended approach, it can be necessary in some cases. This section will explore different approaches for importing and using CommonJS modules inside ES modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*mG9y7EzHqQqhDXoGRytIng.png" /><figcaption>Using CommonJS modules inside ES6 Node or Browser module</figcaption></figure><p><strong>NodeJs: </strong>Use import statement to use CommonJS modules inside an ES module</p><blockquote>⚡️ <a href="https://stackblitz.com/edit/github-nofjl9-czkj4a?file=demo03-ES6-CJS-NODE/package.json">Check Stackblitz for live demo</a></blockquote><p>Use import statement to use CommonJS modules inside an ES module</p><pre>// myModule.cjs<br>module.exports.myFunction = function() {<br>  console.log(&#39;CommonJS Module in ES6 Node module&#39;);<br>}<br><br>// index.js<br>import { myFunction } from &quot;./myModule.cjs&quot;;<br>myFunction();</pre><p><strong>Browser</strong></p><blockquote>⚡️ <a href="https://stackblitz.com/edit/github-nofjl9-czkj4a?file=demo04-ES6-CJS-BROWSER/package.json">Check Stackblitz for live demo</a></blockquote><p>In the browser, there is no built-in support for CommonJS `require` and `exports` syntax, so we cannot use it directly. However, we can still use Webpack to bundle the CommonJS module into a format that can be used in the browser.</p><pre>// package.json<br>{<br>  &quot;name&quot;: &quot;es6-cjs-browser&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;main&quot;: &quot;dist/main.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;webpack &amp;&amp; python3 -m http.server 1111&quot;<br>  },<br>  &quot;type&quot;: &quot;module&quot;<br>}<br><br>// myModule.cjs<br>module.exports.myFunction = function() {<br>  return &#39;CommonJS module in ES6 browser module&#39;;<br>}<br><br>// index.js<br>import { myFunction } from &#39;./myModule.cjs&#39;;<br>function component() {<br>  const element = document.createElement(&quot;div&quot;);<br>  element.innerHTML += myFunction();<br>  return element;<br>}<br>document.body.appendChild(component());</pre><p>After running `webpack`, a `main.js` file will be created in the `dist` directory. This file can be used as an ES6 module inside the HTML script tag to run it in browser.</p><pre>// index.html<br>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Browser ES6 Module demo&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;script src=&quot;../dist/main.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><h3>Conclusion</h3><p>JavaScript modules are a powerful tool for organizing and modularizing your code. They allow you to write code that is more maintainable, testable, and reusable.</p><p>There are several different types of JavaScript modules, including CommonJS modules and ES modules. CommonJS modules are used in Node.js, while ES modules are used in the browser. However, with the help of module bundlers like Webpack, you can use both types of modules in your JavaScript code.</p><p>When using CommonJS modules with Webpack, you can simply import them using the require() function in your JavaScript code. When using ES modules with Webpack, you need to use the import and export keywords in your JavaScript code, and use the babel-loader plugin to transpile your ES modules to JavaScript that can be understood by all browser versions.</p><p>Overall, JavaScript modules and module bundlers are an important part of modern web development, and can help you write more organized, maintainable, and scalable code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37029d57c6ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>