Circular Dependency Plugin

raw JSON →
5.2.2 verified Sat Apr 25 auth: no javascript

A webpack plugin that detects modules with circular dependencies during the bundling process. Current stable version is 5.2.2, released in 2021, with infrequent updates due to stability. It integrates deeply with webpack's compilation lifecycle, offering hooks like onStart, onDetected, and onEnd for custom handling, and supports excluding/including files via RegExp. Unlike static analysis tools, it works on webpack's resolved module graph. Requires webpack >=4.0.1 as a peer dependency.

error TypeError: CircularDependencyPlugin is not a constructor
cause Importing as default export instead of the correct import pattern.
fix
Use const CircularDependencyPlugin = require('circular-dependency-plugin'); with new.
error Circular dependency detected: src/a.js -> src/b.js -> src/a.js
cause Actual circular import in your codebase.
fix
Refactor code to break the cycle or add the cycle to an exclusion list.
error Plugin circular-dependency-plugin is not compatible with webpack 3. Please upgrade to webpack 4 or higher.
cause Using version 5 of the plugin with webpack 3.
fix
Downgrade to circular-dependency-plugin@4 or upgrade webpack to >=4.0.1.
gotcha Plugin only works on modules that webpack resolves; it does not detect cycles from dynamic imports unless allowAsyncCycles is set to false.
fix Set allowAsyncCycles: false to detect cycles involving async imports (default behavior).
breaking Version 5 dropped support for webpack 3.x and below. Only webpack >=4.0.1 is supported.
fix If using webpack 3.x, use circular-dependency-plugin@4 or lower.
deprecated The `cwd` option is deprecated in favor of using module context directly.
fix Remove the `cwd` option; webpack's internal module resolution handles it.
gotcha Setting `failOnError: true` will cause webpack to emit errors instead of warnings, potentially breaking the build.
fix Use `failOnError: false` to emit warnings only (default).
npm install circular-dependency-plugin
yarn add circular-dependency-plugin
pnpm add circular-dependency-plugin

Webpack configuration integrating CircularDependencyPlugin to detect and warn on circular imports.

// webpack.config.js
const path = require('path');
const CircularDependencyPlugin = require('circular-dependency-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  plugins: [
    new CircularDependencyPlugin({
      exclude: /node_modules/,
      include: /dir/,
      failOnError: false,
      allowAsyncCycles: false,
      cwd: process.cwd(),
      onDetected({ module: webpackModuleRecord, paths, compilation }) {
        compilation.warnings.push(new Error(paths.join(' -> ')));
      }
    })
  ]
};