detectDeadCodePlugin.js 1.16 KB
Newer Older
邓晓峰's avatar
邓晓峰 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
const { detectDeadCode, disabledFolders } = require('./detectDeadCode');
// eslint-disable-next-line import/extensions
const { Env } = require('../types');
const defaultOptions = {
  patterns: [`!(${disabledFolders.join('|')})/**/*.*`],
  exclude: [],
  failOnHint: false,
  detectUnusedFiles: true,
  detectUnusedExport: true,
};

class DetectDeadCodePlugin {
  options = defaultOptions;

  constructor(options) {
    if (!options) {
      return;
    }

    this.options = {
      ...this.options,
      ...options,
    };
  }

  apply(compiler) {
    if (!this.options.context) {
      this.options = {
        ...this.options,
        context: compiler.context,
      };
    }

    compiler.hooks.afterEmit.tapAsync('DetectDeadCodePlugin', this.handleAfterEmit);
  }

  handleAfterEmit = (compilation, callback) => {
    detectDeadCode(compilation, this.options);
    callback();
  };
}

module.exports = async function addDetectDeadCodePlugin(opts) {
  const { config, userConfig } = opts;
  const isDev = opts.env === Env.development;

  if (userConfig.deadCode && !isDev) {
    config.plugin('detect-dead-code-plugin').use(DetectDeadCodePlugin, [userConfig.deadCode]);
  }
};