webpack常用插件

224 阅读1分钟

clean-webpack-plugin

我们每次打包都会生成新的文件,那么在一次打包之前,肯定是要把之前生成的文件给清除啦

const {CleanWebpackPlugin} = require('clean-webpack-plugin');
new CleanWebpackPlugin()

html-webpack-plugin

这个插件顾名思义,就是打包生存html用的

const HtmlWebpackPlugin = require('html-webpack-plugin');
new HtmlWebpackPlugin({
    title : pages[key].title,
    filename : key + '.htm',
    template: pages[key].template || './src/template.htm',
    inject : false,
    hash : true,
    jsList : pages[key].jsList || []
})

progress-bar-webpack-plugin

我们每次在编译的时候,还是希望能够看到webpack打包的进度,用这个插件就好

const ProgressBarPlugin = require('progress-bar-webpack-plugin');
new ProgressBarPlugin();

happypack

由于webpack打包属于单线程打包,速度是非常慢的,特别是多文件打包应用中。happypack可以为我们提供多线程打包,优化打包速度

const HappyPack = require('happypack')
//配置线程池
const happyThreadPool = HappyPack.ThreadPool({
    size: 5
})
plugins = [
    new HappyPack({
        id: 'babel',
        loaders: [
        {
            path: 'babel-loader',
            cache: true,
            query: {
                cacheDirectory:true,
                compact:false,
                presets: ['react', 'es2015'],
            }
        }],
        threadPool: happyThreadPool,
        verbose: true
    }),
    new HappyPack({
        id: 'css',
        loaders: ['style-loader', 'css-loader'],
        threadPool: happyThreadPool,
        verbose: true
    }),
    new HappyPack({
        id: 'less',
        loaders: [
            'style-loader', 'css-loader',  'less-loader'],
        threadPool: happyThreadPool,
        verbose: true
    })
];
module: {
    rules: [
        {
            test: /\.js$/,
            use: ['happypack/loader?id=babel'],
            exclude: path.resolve(__dirname, 'node_modules'), //排除node_modules目录,该目录不参与编译
        },
        {
            test: /\.css$/,
            use:['happypack/loader?id=css'],
        },
        {
            test: /\.less$/,
            use: ['happypack/loader?id=less'],
            exclude: path.resolve(__dirname, 'node_modules'),
        }
    ]
}