webpack3--plugins大用处

3,196 阅读3分钟

要想让webpack为我所用,不仅要求我们在loader使用上得心应手,更离不开对plugins的熟练使用。

Pre:本文,承接loader全解析

如果说把webpack比喻成一台豆浆机,我们需要一杯豆浆喝,我们要:

  1. 准备好原材料,好比我们的 entry 入口起点的处理;
  2. 选择豆浆品种,好比我们在选择 loader 加载器;
  3. 搅拌电机工作,好比我们 plugins 插件的大用处;
  4. 完成倒出品尝,好比我们 output 输出文件的处理;
  5. 电力保障在线,好比我们 devServer 服务开启。
    这一形象的比喻,目的在于帮助我们理解webpack的工作机制,要想用好它,就必须清楚每个module的原理和使用方法。

    下面重点谈谈plugins的大用处:

    插件(plugins)

    loader 仅在每个文件的基础上执行转换,而 插件(plugins) 更常用于(但不限于)在打包模块的 “compilation” 和 “chunk” 生命周期执行操作和自定义功能。webpack 的插件系统极其强大和可定制化。
  • 使用方法:
    想要使用一个插件,你只需要 require() 它,然后把它添加到 plugins 数组中。
    多数插件可以通过选项(option)自定义。你也可以在一个配置文件中因为不同目的而多次使用同一个插件,这时需要通过使用 new 来创建它的一个实例。
    在webpack.config.js配置如下:

    const HtmlWebpackPlugin = require('html-webpack-plugin');
    const webpack = require('webpack');
    const path = require('path');
    const config = {
    //入口配置
    entry: './path/to/my/entry/file.js',
    //输出配置
    output: {
      path: path.resolve(__dirname, 'dist'),
      filename: 'my-first-webpack.bundle.js'
    },
    //模块loader加载转换
    module: {
      rules: [
        { test: /\.txt$/, use: 'raw-loader' }
      ]
    },
    //插件调用完成功能定制
    plugins: [
      //压缩js插件
      new webpack.optimize.UglifyJsPlugin(),
      //以index.html文件为模板生成html5新文件
      new HtmlWebpackPlugin({template: './src/index.html'})
    ]
    };
    module.exports = config;

    常用webpack插件举例

    webpack 有着丰富的插件接口(rich plugin interface)。webpack 自身的多数功能都使用这个插件接口。这个插件接口使 webpack 变得极其灵活。
    更多插件使用还请移步官网

  • CommonsChunkPlugin
    The CommonsChunkPlugin is an opt-in feature that creates a separate file (known as a chunk), consisting of common modules shared between multiple entry points. By separating common modules from bundles, the resulting chunked file can be loaded once initially, and stored in cache for later use. This results in pagespeed optimizations as the browser can quickly serve the shared code from cache, rather than being forced to load a larger bundle whenever a new page is visited.
    大致翻译过来就是这个插件可以帮助你从众多模块中抽离并合并出一个公共模块文件,浏览器只加载一次即可,给页面加载带来速度上的提升。
    注意: 此插件属于webpack内置 无需安装

使用方法:
new webpack.optimize.CommonsChunkPlugin(options)

配置:

{
  name: string, // or
  names: string[],
  // 这是 common chunk 的名称。已经存在的 chunk 可以通过传入一个已存在的 chunk 名称而被选择。
  // 如果一个字符串数组被传入,这相当于插件针对每个 chunk 名被多次调用

  filename: string,
  // common chunk 的文件名模板。可以包含与 `output.filename` 相同的占位符。

  minChunks: number|Infinity|function(module, count) -> boolean,
  // 在传入  公共chunk(commons chunk) 之前所需要包含的最少数量的 chunks 。
  // 数量必须大于等于2,或者少于等于 chunks的数量

  chunks: string[],
  // 通过 chunk name 去选择 chunks 的来源。chunk 必须是  公共chunk 的子模块。
  // 如果被忽略,所有的,所有的 入口chunk (entry chunk) 都会被选择。

  children: boolean,
  // 如果设置为 `true`,所有  公共chunk 的子模块都会被选择

  deepChildren: boolean,
  // If `true` all descendants of the commons chunk are selected

  async: boolean|string,
  // 如果设置为 `true`,一个异步的  公共chunk 会作为 `options.name` 的子模块,和 `options.chunks` 的兄弟模块被创建。

  minSize: number,
  // 在 公共chunk 被创建立之前,所有 公共模块 (common module) 的最少大小。
}

举例:

// 提取公共文件
new webpack.optimize.CommonsChunkPlugin({
    name: 'reset',
    filename: 'vendor/common.js',
    //(模块必须被3个 入口chunk 共享)
    minChunks: 3
}),
  • ExtractTextWebpackPlugin
    Extract text from a bundle, or bundles, into a separate file.
    这个插件是用来分离的,出单独的一个文件

安装:

npm install --save-dev extract-text-webpack-plugin

使用方法:

const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
   module: {
     rules: [
       {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: "css-loader"
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin("styles.css"),
  ]
}

它会将所有的入口 chunk(entry chunks)中引用的 *.css,移动到独立分离的 CSS 文件。因此,你的样式将不再内嵌到 JS bundle 中,而是会放到一个单独的 CSS 文件(即 styles.css)当中。

  • HotModuleReplacementPlugin
    模块热替换插件,启用热替换模块(Hot Module Replacement),也被称为 HMR。
    注意:永远不要在生产环境(production)下启用 HMR
    用法:
    启用 HMR 非常简单,在大多数情况下也不需要设置选项。
    new webpack.HotModuleReplacementPlugin({
       // Options...
    })
  • HtmlWebpackPlugin
    它简化了HTML文件的创建,以便为您的webpack包提供服务。 这对于在文件名中包含每次会随着变异会发生变化的哈希的webpack bundle尤其有用。

安装

npm install --save-dev html-webpack-plugin

使用方法:
SPA单页面时:

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

var webpackConfig = {
  entry: 'index.js',
  output: {
    path: 'dist',
    filename: 'index_bundle.js'
  },
  plugins: [new HtmlWebpackPlugin()]
};
module.exports = webpackConfig;

这将会产生一个包含以下内容的文件 dist/index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>webpack App</title>
  </head>
  <body>
    <script src="index_bundle.js"></script>
  </body>
</html>

多页面时:

{
  entry: 'index.js',
  output: {
    path: __dirname + '/dist',
    filename: 'index_bundle.js'
  },
  plugins: [
    new HtmlWebpackPlugin(), // Generates default index.html
    new HtmlWebpackPlugin({  // Also generate a test.html
      filename: 'test.html',
      template: 'src/assets/test.html'
    })
  ]
}
  • ProvidePlugin
    自动加载模块,而不必到处 import 或 require 。
    当我们的应用大量使用jQuery或Zepto时,可以借助此插件实现一次认定,到处使用。
    注意:webpack内置,不用安装
    要自动加载 jquery,我们可以将两个变量都指向对应的 node 模块:
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery'
    })
    使用:Lodash Map
    new webpack.ProvidePlugin({
      _map: ['lodash', 'map']
    })
  • UglifyjsWebpackPlugin
    to minify your JavaScript
    这个插件用来压缩你的js的,uglify翻译过来是丑化,弄的难看,就是要变成在一堆的代码,从而减小代码文件的体积。

安装:

npm i -D uglifyjs-webpack-plugin

使用方法:

const UglifyJSPlugin = require('uglifyjs-webpack-plugin')

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

配置项:

{
    parse: {
        // parse options
    },
    compress: {
        // compress options
    },
    mangle: {
        // mangle options

        properties: {
            // mangle property options
        }
    },
    output: {
        // output options
    },
    sourceMap: {
        // source map options
    },
    ecma: 5, // specify one of: 5, 6, 7 or 8
    nameCache: null, // or specify a name cache object
    toplevel: false,
    ie8: false,
    warnings: false,
}

更多参数请参考Uglifyjs官网