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

相關文章
相關標籤/搜索