[Webpack] Detect Unused Code with Webpack and unused-files-webpack-plugin

As you refactor and modify applications, it's difficult to manage and keep track of files as they become unused. Keeping this "dead" code around adds noise to your application and reduces clarity. Just as ESLint can tell us when variables become unused, Webpack (with the help of the unused-files-webpack-plugin) can tell us when entire files become unused. First, we'll install the plugin with npm and save it as a devDependency. Next, we'll use npm run scripts to build a new command that will run Webpack with the plugin. Finally, we'll learn how to use Webpack environment variables to conditionally add plugins to your Webpack config. By the end of the lesson, you'll have a useful cli command you can run to check for unused modules in your Webpack build

 

Install:

npm i -D unused-files-webpack-plugin

 

Update scripts:

"check-unused": "webpack --mode production --env.unused=true --display=errors-only",

 

Update webpack.config.js:

/* eslint-env node */
const UnusedFilesPlugin = require('unused-files-webpack-plugin').default;

module.exports = (env) => {
    const config = {
        entry: './src/index.js'
    };

    if (env && env.unused) {
        config.plugins = [
            new UnusedFilesPlugin({
                failOnUnused: true,
                patterns: ['src/*.js']
            })
        ]
    }

    return config;
};

 

转载于:https://www.cnblogs.com/Answer1215/p/10339389.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值