webpack3--plugins大用处

要想让webpack为我所用,不只要求咱们在loader使用上驾轻就熟,更离不开对plugins的熟练使用。css

Pre:本文,承接loader全解析html

若是说把webpack比喻成一台豆浆机,咱们须要一杯豆浆喝,咱们要:html5

  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配置以下:node

    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 变得极其灵活。
    更多插件使用还请移步官网jquery

  • 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内置 无需安装 webpack

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

配置:github

{
  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) 的最少大小。
}复制代码

举例:web

// 提取公共文件
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

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官网

相关文章
相关标签/搜索