webpack学习笔记—plugins

plugins来啦~plugins是为了解决loader没法解决的事情~
plugins:Array
插件能够携带参数/选项,在config配置中,向plugins传入new实例。下面列举了一些经常使用plugin~javascript

1.html-webpack-plugin:html入口文件
这个插件主要有两个用处:
1). 为html文件引入外部资源,如打包生成的js、css等,每次构建后不须要本身手动修改;
2). 生成建立html文件,一个html文件对应一个入口,能够配置N个html-webpack-plugin生成N个入口~也能够经过函数批量生成~css

// html入口
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    plugins: [
        // 单个入口配置
        new HtmlWebpackPlugin({
            template: path.join(__dirname, 'src/index.html'),
            filename: 'search.html',
            // 使用chunk,与注入的打包好的文件名对应
            chunks: ['search'],
            // 打包出的chunk自动注入
            inject: true,
            minify: {
                html5: true,
                // 删除空格和换行符,若preserveLineBreaks参数设为true,则保留了换行符
                collapseWhitespace: true,
                preserveLineBreaks: false,
                minifyCSS: true,
                minifyJS: true,
                removeComments: false
            }
        })
    ]
};

以上是单个入口的配置,若须要配置多个入口呢?能够依次添加多个,也能够经过函数生成,相似多文件入口的作法,在以前的entry篇提到过,此次就在以前函数的基础s上进行扩展~html

const setMPA = () => {
    const entry = {};
    const htmlWebpackPlugins = [];

    const entryFiles = glob.sync(path.join(__dirname, './src/*/index.js'));
    Object.keys(entryFiles).map(index => {
        const entryFile = entryFiles[index];
        const match = entryFile.match(/src\/(.*)\/index\.js/);
        const pageName = match && match[1];
        entry[pageName] = entryFile;
        const htmlWebpackPlugin = new HtmlWebpackPlugin({
            template: path.join(__dirname, `src/${pageName}/index.html`),
            filename: `${pageName}.html`,
            // 使用chunk
            chunks: [pageName],
            // 打包出的chunk自动注入
            inject: true,
            minify: {
                html5: true,
                // 删除空格和换行符,若preserveLineBreaks参数设为true,则保留了换行符
                collapseWhitespace: true,
                preserveLineBreaks: false,
                minifyCSS: true,
                minifyJS: true,
                removeComments: false
            }
        });
        htmlWebpackPlugins.push(htmlWebpackPlugin);
    });
    return {
        entry,
        htmlWebpackPlugins
    };
};

const {entry, htmlWebpackPlugins} = setMPA();

// 直接在plugins的值上进行拼接
module.exports = {
    plugins: [].concat(htmlWebpackPlugins)
};

2.optimize-css-assets-webpack-plugin:压缩CSS
配合cssnano使用,对CSS作多方面的优化,保证最终生成的文件体积是最小的。html5

// css压缩
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');

plugins: [
    new OptimizeCSSAssetsPlugin({
        assetNameRegExp: /\.css$/g,
        cssProcessor: require('cssnano')
    })
]

3.mini-css-extract-plugin:抽离CSS为单独文件java

// 将CSS抽离成单独文件
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports ={
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader'
                ]
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: '[name]_[contenthash:8].css'
        })
    ]  
};

使用时须要和loader结合使用,解析CSS时先用CSS-loader进行解析,而后经过MiniCssExtractPlugin.loader将CSS抽离成单独文件~在服务端渲染推荐使用~node

4.clean-webpack-plugin:清理构建产物
每次打包都会生成dist文件夹,执行构建以前不删除的话,dist目录会愈来愈大~解决这种请求,有两种方法:
1).在package.json中配置命令react

// package.json
"scripts": {
    "build": "rm -rf ./dist && build"
}

2).使用插件clean-webpack-plugin
注意:node v8.0+ && webpack v3.0+webpack

// 清理构建产物,新版按需引入,不能直接引入
// TypeError: CleanWebpackPlugin is not a constructor
const {CleanWebpackPlugin} = require('clean-webpack-plugin');

plugins: [
    new CleanWebpackPlugin()
]

这里,须要注意下版本~老版本能够直接引入,新版须要按需引入~目前我引用的是3.0版本,须要按需引入~你们使用的时候能够注意下,若是比3.0版本旧的话,能够先尝试直接引入,若是报错TypeError: CleanWebpackPlugin is not a constructor,再修改成按需引入~git

5.html-webpack-externals-plugin:基础库不打包,直接CDN引入
开发时,有时候须要引入一些基础库,如react开发时,每一个组件都须要引入react和react-dom,咱们打包时这两个基础库提交较大,致使构建出来的包提交变大~这个时候,咱们能够考虑将react和react-dom在html中用CDN引入~github

// wepack.config.js
// 基础库不打包,直接CDN引入
const HtmlWebpackExternalsPlugin = require('html-webpack-externals-plugin');

module.exports = {
    new HtmlWebpackExternalsPlugin({
        externals: [
            {
                module: 'react',
                entry: 'https://11.url.cn/now/lib/16.2.0/react.min.js',
                global: 'React'
            },
            {
                module: 'react-dom',
                entry: 'https://11.url.cn/now/lib/16.2.0/react-dom.min.js',
                global: 'ReactDOM'
            }
        ]
    })
};

// index.html
<script type="text/javascript" src="https://11.url.cn/now/lib/16.2.0/react.min.js"></script>
<script type="text/javascript" src="https://11.url.cn/now/lib/16.2.0/react-dom.min.js"></script>

6.friendly-errors-webpack-plugin:构建日志优化提示
执行构建时,每次都输出好多内容,有的时候,咱们实际上是不关注构建过程和构建结果的,只关心构建是否成功。这个插件就是一个不错的选择~

// 构建日志优化提示
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');

module.exports = {
    plugins: [
        new FriendlyErrorsWebpackPlugin()
    ]
};

还有一种方式能够改变输出内容,配置stats

module.exports = {
    stats: 'errors-only'
};

若是使用了webpack-dev-server,则stats这个配置项须要放在devServer中~

devServer: {
    contentBase: './dist/',
    hot: true,
    stats: 'errors-only'
}

暂时就到这里了~源码请移步demo