<?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 linx4200 on Medium]]></title>
        <description><![CDATA[Stories by linx4200 on Medium]]></description>
        <link>https://medium.com/@tonibellbell?source=rss-544a2f5a61e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jhs-drdjrEx8aSxPq9g_YQ.png</url>
            <title>Stories by linx4200 on Medium</title>
            <link>https://medium.com/@tonibellbell?source=rss-544a2f5a61e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:32:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tonibellbell/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[# Resolving Circular Dependency Issues in ES5 Projects with Webpack and ESLint]]></title>
            <link>https://medium.com/@tonibellbell/resolving-circular-dependency-issues-in-es5-projects-with-webpack-and-eslint-8138f704f851?source=rss-544a2f5a61e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8138f704f851</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[linx4200]]></dc:creator>
            <pubDate>Mon, 20 May 2024 08:08:44 GMT</pubDate>
            <atom:updated>2024-05-20T08:23:15.321Z</atom:updated>
            <content:encoded><![CDATA[<h3>Resolving Circular Dependency Issues in ES5 Projects with Webpack and ESLint</h3><p>A Guide to Identifying and Fixing Circular Dependencies in JavaScript Projects Using Madge and ESLint</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ib5Z-aN-2Ak4J2Mk6DKVYA.jpeg" /></figure><h4>TL;DR</h4><p>- It is recommended to use ESLint with the rule to check for circular dependencies in your project.<br>- If your build target is ES5, once a module exports constants, it should not import other modules.</p><h4>Issue Symptoms</h4><p>When running the project, a constant referenced is output as `undefined`.</p><p>For example: `FOO` exported from `utils.js` is imported in `index.js` and its value is printed as `undefined`.</p><pre>// utils.js<br>// import other modules…<br>export const FOO = &#39;foo&#39;;<br>// more other codes….<br>```<br>```javascript<br>// index.js<br>import { FOO } from &#39;./utils.js&#39;;<br>// import other modules…<br>console.log(FOO); // `console.log` outputs `undefined`<br>// more other codes…</pre><p>Based on experience, this issue is likely caused by a circular dependency between `index.js` and `utils.js`.</p><p>The next step is to identify the circular dependency path between the two modules to verify the hypothesis.</p><h4>Finding Circular Dependencies</h4><p><strong>Install Madge Tool</strong></p><p>There are many tools available in the community for finding circular dependencies. Here, we use <a href="https://www.npmjs.com/package/madge">Madge</a> as an example.</p><blockquote>Madge is a developer tool for generating a visual graph of your module dependencies, finding circular dependencies, and providing other useful information.</blockquote><p>Step 1: Configure Madge</p><pre>// madge.js<br>const madge = require(&quot;madge&quot;);<br>const path = require(&quot;path&quot;);<br>const fs = require(&quot;fs&quot;);<br>madge(&quot;./index.ts&quot;, {<br>  tsConfig: {<br>    compilerOptions: {<br>      paths: {<br>        // specify path aliases if using any<br>      },<br>    },<br>  },<br>})<br>  .then((res) =&gt; res.circular())<br>  .then((circular) =&gt; {<br>    if (circular.length &gt; 0) {<br>      console.log(&quot;Found circular dependencies: &quot;, circular);<br>      // save the result into a file<br>      const outputPath = path.join(__dirname, &quot;circular-dependencies.json&quot;);<br>      fs.writeFileSync(outputPath, JSON.stringify(circular, null, 2), &quot;utf-8&quot;);<br>      console.log(`Saved to ${outputPath}`);<br>    } else {<br>      console.log(&quot;No circular dependencies found.&quot;);<br>    }<br>  })<br>  .catch((error) =&gt; {<br>    console.error(error);<br>  });</pre><p>Step 2: Run the Script</p><pre>node madge.js</pre><p>After running the script, a 2D array is obtained.</p><p>The 2D array stores all the circular dependencies in the project. Each sub-array represents a specific circular dependency path: file at index `n` references the file at index `n + 1`, and the last file references the first file, forming a circular dependency.</p><p>It’s important to note that Madge can only return direct circular dependencies. If two files form an indirect circular dependency through a third file, it will not be included in Madge’s output.</p><p>Based on the actual project situation, Madge output a result file with over 6,000 lines. The result file shows that the suspected circular dependency between the two files is not directly referenced. Finding the indirect dependency between the two target files was like searching for a needle in a haystack.</p><p><strong>Writing a Script to Find Indirect Circular Dependencies</strong></p><p>Next, I asked ChatGPT to help write a script to find direct or indirect circular dependency paths between two target files based on the result file.</p><pre>/**<br> * Check if there is a direct or indirect circular dependency between two files<br> * @param {Array&lt;string&gt;} targetFiles Array containing two file paths<br> * @param {Array&lt;Array&lt;string&gt;&gt;} references 2D array representing all file dependencies in the project<br> * @returns {Array&lt;string&gt;} Array representing the circular dependency path between the two target files<br> */<br>function checkCircularDependency(targetFiles, references) {<br>  // Build graph<br>  const graph = buildGraph(references); // Store visited nodes to avoid revisiting<br>  let visited = new Set(); // Store the current path to detect circular dependencies<br>  let pathStack = [];<br>  // Depth-First Search<br>  function dfs(node, target, visited, pathStack) {<br>    if (node === target) {<br>      // Found target, return path<br>      pathStack.push(node);<br>      return true;<br>    }<br>    if (visited.has(node)) {<br>      return false;<br>    }<br>    visited.add(node);<br>    pathStack.push(node);<br>    const neighbors = graph[node] || [];<br>    for (let neighbor of neighbors) {<br>      if (dfs(neighbor, target, visited, pathStack)) {<br>        return true;<br>      }<br>    }<br>    pathStack.pop();<br>    return false;<br>  }<br>  // Build graph<br>  function buildGraph(references) {<br>    const graph = {};<br>    references.forEach((ref) =&gt; {<br>      for (let i = 0; i &lt; ref.length; i++) {<br>        const from = ref[i];<br>        const to = ref[(i + 1) % ref.length]; // Circular reference to the first element<br>        if (!graph[from]) {<br>          graph[from] = [];<br>        }<br>        graph[from].push(to);<br>      }<br>    });<br>    return graph;<br>  }<br>  // Try to find the path from the first file to the second file<br>  if (dfs(targetFiles[0], targetFiles[1], new Set(), [])) {<br>    // Clear visited records and path stack, try to find the path from the second file back to the first file<br>    visited = new Set();<br>    pathStack = [];<br>    if (dfs(targetFiles[1], targetFiles[0], visited, pathStack)) {<br>      return pathStack;<br>    }<br>  }<br>  // If no circular dependency is found, return an empty array<br>  return [];<br>}<br>// Example usage<br>const targetFiles = [<br>  &quot;scene/home/controller/home-controller/grocery-entry.ts&quot;,<br>  &quot;../../request/api/home.ts&quot;,<br>];<br>const references = require(&quot;./circular-dependencies&quot;);<br>const circularPath = checkCircularDependency(targetFiles, references);<br>console.log(circularPath);</pre><p>Using the 2D array output from Madge as the script input, the result indicated that there was indeed a circular dependency between `index.js` and `utils.js`, consisting of a chain involving 26 files.</p><h4>Root Cause</h4><p>Before solving the problem, we need to understand the root cause: Why does circular dependency cause the referenced constant to be `undefined`?</p><p>To simulate and simplify the problem, let’s assume the circular dependency chain is as follows:</p><p>index.js → component-entry.js → request.js → utils.js → component-entry.js</p><p>Since the project code is ultimately bundled by Webpack and compiled into ES5 code using Babel, we need to look at the structure of the bundled code.</p><p><strong>Example of Webpack Bundled Code</strong></p><pre>(() =&gt; {<br>  &quot;use strict&quot;;<br><br>  var e,<br>    __modules__ = {<br>      /* ===== component-entry.js starts ==== */<br>      148: (_, exports, __webpack_require__) =&gt; {<br>        // [2] define the getter of `exports` properties of `component-entry.js`<br>        __webpack_require__.d(exports, { Cc: () =&gt; r, bg: () =&gt; c });<br>        // [3] import `request.js`<br>        var t = __webpack_require__(595);<br>        // [9]<br>        var r = function () {<br>            return (<br>              console.log(&quot;A function inside component-entry.js run, &quot;, c)<br>            );<br>          },<br>          c = &quot;An constants which comes from component-entry.js&quot;;<br>      },<br>      /* ===== component-entry.js ends ==== */<br><br>      /* ===== request.js starts ==== */<br>      595: (_, exports, __webpack_require__) =&gt; {<br>        // [4] import `utils.js`<br>        var t = __webpack_require__(51);<br>        // [8]<br>        console.log(&quot;request.js run, two constants from utils.js are: &quot;, t.R, &quot;, and &quot;, t.b);<br>      },<br>      /* ===== request.js ends ==== */<br><br>      /* ===== utils.js starts ==== */<br>      51: (_, exports, __webpack_require__) =&gt; {<br>        // [5] define the getter of `exports` properties of `utils.js`<br>        __webpack_require__.d(exports, { R: () =&gt; r, b: () =&gt; t.bg });<br>        // [6] import `component-entry.js`, `component-entry.js` is already in `__webpack_module_cache__`<br>        // so `__webpack_require__(148)` will return the `exports` object of `component-entry.js` immediately<br>        var t = __webpack_require__(148);<br>        var r = 1001;<br>        // [7] print the value of `bg` exported by `component-entry.js`<br>        console.log(&#39;utils.js,&#39;, t.bg); // output: &#39;utils, undefined&#39;<br>      },<br>      /* ===== utils.js starts ==== */<br>    },<br><br>    __webpack_module_cache__ = {};<br><br>  function __webpack_require__(moduleId) {<br>    var e = __webpack_module_cache__[moduleId];<br><br>    if (void 0 !== e) return e.exports;<br><br>    var c = (__webpack_module_cache__[moduleId] = { exports: {} });<br><br>    return __modules__[moduleId](c, c.exports, __webpack_require__), c.exports;<br>  }<br><br>  // Adds properties from the second object to the first object<br>  __webpack_require__.d = (o, e) =&gt; {<br>    for (var n in e)<br>      Object.prototype.hasOwnProperty.call(e, n) &amp;&amp;<br>        !Object.prototype.hasOwnProperty.call(o, n) &amp;&amp;<br>        Object.defineProperty(o, n, { enumerable: !0, get: e[n] });<br>  },<br><br>  // [0]<br>  // ======== index.js starts ========<br>  // [1] import `component-entry.js`<br>  (e = __webpack_require__(148/* (148 is the internal module id of `component-entry.js`) */)),<br>  // [10] run `Cc` function exported by `component-entry.js`<br>  (0, e.Cc)();<br>  // ======== index.js ends ========<br>})();</pre><p>In the example, [number] indicates the execution order of the code.</p><p>Simplified version:</p><pre>function lazyCopy (target, source) {<br>  for (var ele in source) {<br>    if (Object.prototype.hasOwnProperty.call(source, ele)<br>      &amp;&amp; !Object.prototype.hasOwnProperty.call(target, ele)<br>    ) {<br>      Object.defineProperty(target, ele, { enumerable: true, get: source[ele] });<br>    }<br>  }<br>}<br><br>// Assuming module1 is the module being cyclically referenced (module1 is a webpack internal module, actually representing a file)<br>var module1 = {};<br>module1.exports = {};<br>lazyCopy(module1.exports, { foo: () =&gt; exportEleOfA, print: () =&gt; print, printButThrowError: () =&gt; printButThrowError });<br>// module1 is initially imported at this point<br><br>// Assume the intermediate process is omitted: module1 references other modules, and those modules reference module1<br><br>// When module1 is imported a second time and its `foo` variable is used, it is equivalent to executing:<br>console.log(&#39;Output during circular reference (undefined is expected): &#39;, module1.exports.foo); // Output `undefined`<br><br>// Call `print` function, which can be executed normally due to function scope hoisting<br>module1.exports.print(); // &#39;print function executed&#39;<br><br>// Call `printButThrowError` function, which will throw an error due to the way it is defined<br>try {<br>  module1.exports.printButThrowError();<br>} catch (e) {<br>  console.error(&#39;Expected error: &#39;, e); // Error: module1.exports.printButThrowError is not a function<br>}<br><br>// Assume the intermediate process is omitted: all modules referenced by module1 are executed<br><br>// module1 returns to its own code and continues executing its remaining logic<br>var exportEleOfA = &#39;foo&#39;;<br>function print () {<br>  console.log(&#39;print function executed&#39;);<br>}<br>var printButThrowError = function () {<br>  console.log(&#39;printButThrowError function executed&#39;);<br>}<br><br>console.log(&#39;Normal output: &#39;, module1.exports.foo); // &#39;foo&#39;<br>module1.exports.print(); // &#39;print function executed&#39;<br>module1.exports.printButThrowError(); // &#39;printButThrowError function executed&#39;</pre><p><strong>Extension: Webpack Module Bundling Process</strong></p><p>During the AST analysis phase, Webpack looks for ES6 `import` and `export` statements. If a file contains these statements, Webpack marks the module as “harmony” type and performs corresponding code transformation for `exports`:</p><p><a href="https://github.com/webpack/webpack/blob/c586c7b1e027e1d252d68b4372f08a9bce40d96c/lib/dependencies/HarmonyExportInitFragment.js#L161">https://github.com/webpack/webpack/blob/c586c7b1e027e1d252d68b4372f08a9bce40d96c/lib/dependencies/HarmonyExportInitFragment.js#L161</a></p><p><a href="https://github.com/webpack/webpack/blob/c586c7b1e027e1d252d68b4372f08a9bce40d96c/lib/RuntimeTemplate.js#L164">https://github.com/webpack/webpack/blob/c586c7b1e027e1d252d68b4372f08a9bce40d96c/lib/RuntimeTemplate.js#L164</a></p><p><strong>Summary of Root Cause</strong></p><ol><li>Issue symptom: A module imports a constant, but its actual value is `undefined` when running.</li><li>Conditions for the issue to occur:</li></ol><ul><li>The project is bundled by Webpack and compiled into ES5 code (not tested with other bundlers).</li><li>Module A defines a constant `foo` and exports it, and this module has circular dependencies with other modules.</li><li>Module B imports `foo` from Module A and runs during the module initialization process.</li><li>Module A and Module B have a circular dependency.</li></ul><p>3. Root causes:</p><ul><li>In Webpack’s module system, when a module is first referenced, Webpack initializes its `exports` using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get#defining_a_getter_on_existing_objects_using_defineproperty">property getters</a> and stores it in a cache object. When the module is referenced again, it directly returns the `exports` from the cache object.</li><li>`let` variables and `const` constants are compiled into `var` declarations, causing variable hoisting issues. When used before their actual definition, they return `undefined` but do not throw an error.</li><li>Function declarations are hoisted, allowing them to be called normally.</li><li>Arrow functions are compiled into `var foo = function () {};` and function expressions do not have function scope hoisting. Therefore, they throw an error when run instead of returning `undefined`.</li></ul><h4>How to Avoid</h4><p><strong>ESLint</strong></p><p>We can use ESLint to check for circular dependencies in the project. Install the `eslint-plugin-import` plugin and configure it:</p><pre>// babel.config.js<br><br>import importPlugin from &#39;eslint-plugin-import&#39;;<br><br>export default [<br>  {<br>    plugins: {<br>      import: importPlugin,<br>    },<br>    rules: {<br>      &#39;import/no-cycle&#39;: [&#39;error&#39;, { maxDepth: Infinity }],<br>    },<br>    languageOptions: {<br>      &quot;parserOptions&quot;: {<br>        &quot;ecmaVersion&quot;: 6, // or use 6 for ES6<br>        &quot;sourceType&quot;: &quot;module&quot;<br>      },<br>    },<br>    settings: {<br>      // Need this to let &#39;import/no-cycle&#39; to work<br>      // reference: https://github.com/import-js/eslint-plugin-import/issues/2556#issuecomment-1419518561<br>      &quot;import/parsers&quot;: {<br>        espree: [&quot;.js&quot;, &quot;.cjs&quot;, &quot;.mjs&quot;, &quot;.jsx&quot;],<br>      }<br>    },<br>  },<br>];</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8138f704f851" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>