webpack从零开始第4课: 插件篇

webpack目录


本文参考文档

重点插件plugin介绍

  • 插件与模块的功能不一样,模块是为了导入非es5格式js或其它资源类型文件,定制了一些loader。插件是对最后的打包文件进行处理的,也可以理解loader是为打包前做准备,plugin是打包再进行处理
  • 官方插件的使用步骤(内置插件2步)

    • 配置文件中导入webpack const wp= require('webpack')
    • 在plugins这个数组中加入一个插件实例,new wp.XxxxPlugin({对象})
  • 第三方插件的使用步骤(第3方3步,多一次安装)

    • 安装(第三方插件要安装) 根目录>cnpm i -D XxxxPlugin
    • 配置文件中导入插件 const XxxxPlugin = require('xxxx-plugin')
    • 在plugins这个数组中加入一个插件实例,new XxxxPlugin({对象})
  • 官方插件有

    // https://github.com/webpack/webpack/blob/master/lib/webpack.js中exportPlugins部分就是全部内置的插件
    const webpack = require('webpack')
    console.log(webpack ) //这里可以看到哪些是webpack内置的插件
      DefinePlugin //定义一个全局常量,如new wp.DefinePlugin({BJ: JSON.stringify('北京'),}),在待打包的js文件中可以直接使用,如在./src/main.js中console.log('我是在配置文件中定义的'+BJ)
      NormalModuleReplacementPlugin: [Getter],
      ContextReplacementPlugin: [Getter],
      ContextExclusionPlugin: [Getter],
      IgnorePlugin: [Getter],
      WatchIgnorePlugin: [Getter],
      BannerPlugin: [Getter],
      PrefetchPlugin: [Getter],
      AutomaticPrefetchPlugin: [Getter],
      ProvidePlugin: [Getter],
      HotModuleReplacementPlugin: [Getter],
      SourceMapDevToolPlugin: [Getter],
      EvalSourceMapDevToolPlugin: [Getter],
      EvalDevToolModulePlugin: [Getter],
      CachePlugin: [Getter],
      ExtendedAPIPlugin: [Getter],
      ExternalsPlugin: [Getter],
      JsonpTemplatePlugin: [Getter],
      LibraryTemplatePlugin: [Getter],
      LoaderTargetPlugin: [Getter],
      ProgressPlugin: [Getter],
      SetVarMainTemplatePlugin: [Getter],
      UmdMainTemplatePlugin: [Getter],
      NoErrorsPlugin: [Getter],
      NoEmitOnErrorsPlugin: [Getter],
     NewWatchingPlugin: [Getter],
      EnvironmentPlugin: [Getter],
      DllPlugin: [Getter],
      DllReferencePlugin: [Getter],
      LoaderOptionsPlugin: [Getter],
      NamedModulesPlugin: [Getter],
      NamedChunksPlugin: [Getter],
      HashedModuleIdsPlugin: [Getter],
      optimize:
       { AggressiveMergingPlugin: [Getter],
         AggressiveSplittingPlugin: [Getter],
         CommonsChunkPlugin: [Getter],
         ChunkModuleIdRangePlugin: [Getter],
         DedupePlugin: [Getter],
         LimitChunkCountPlugin: [Getter],
         MinChunkSizePlugin: [Getter],
         ModuleConcatenationPlugin: [Getter],
         OccurrenceOrderPlugin: [Getter],
         UglifyJsPlugin: [Getter] }
     }

待讲插件清单
下面以webpack.开头的表示是自带插件,无须另外安装
01: webpack.BannerPlugin 加注释
02: uglifyjs-webpack-plugin 代码缩小
03: html-webpack-plugin 生成html页
04: extract-text-webpack-plugin 提取css等

05: copy-webpack-plugin

插件01 BannerPlugin

作用: 在打包的文件中添加注释
网址: https://webpack.js.org/plugin...

/*! 每一次靠近,总是那么悄悄的 */  //这一行就是使用banner这个插件加入的,利用这个插件可以加在任何打包后的文件中,如js或css文件
/******/ (function(modules) { // webpackBootstrap
const path = require('path');
const webpack = require('webpack')
module.exports={
    context: path.resolve(__dirname,'../today/wang'),
    entry: {
      home: "./home.js",
    },
    output:{
        path: path.resolve(__dirname, "../dist/"),
        filename: "app.js",  
    },
    watch:true,
    devServer: {
      contentBase: path.join(__dirname, "../dist"),
      //compress: true,
      port: 9000,
      hot:true
    },
    plugins: [
        new webpack.BannerPlugin({ //这是webpack内置的插件,所以不用require导入,但是对于第三方插件要先导入
            banner: '每一次靠近,总是那么悄悄的'
        })

    ]    
}

插件02 UglifyjsWebpackPlugin

作用: 乱码,缩小
网址: https://webpack.js.org/plugin...
这个插件不是内置的,要先安装
1.安装
D:\03www2018\study\webpack2017>cnpm i -D uglifyjs-webpack-plugin
2.导入
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
3.配置

const path = require('path');
const webpack = require('webpack')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
module.exports={
    context: path.resolve(__dirname,'../today/wang'),
    entry: {
      home: "./home.js",
    },
    output:{
        path: path.resolve(__dirname, "../dist/"),
        filename: "app.js",  
    },
    watch:true,
    devServer: {
      contentBase: path.join(__dirname, "../dist"),
      //compress: true,
      port: 9000,
      hot:true
    },
    plugins: [
        new webpack.BannerPlugin({
            banner: '每一次靠近,总是那么悄悄的'
        }),
        new UglifyJsPlugin()

    ]    
}

现在代码缩小了,变成

!function(e){function t(e){var t=O[e];if(!t)return c;var n=function(r){return t.hot.active?(O[r]?O[r].parents.indexOf(e)<0&&O[r].parents.push(e):(b=[e],u=r),t.children.indexOf(r)<0&&t.children.push(r)):(console.warn("[HMR] unexpected require("+r+") from disposed module "+e),b=[]),c(r)},o=function(e){return{configurable:!0,enumerable:!0,get:function(){return c[e]},set:function(t){c[e]=t}}};for(var a in c)Object.prototype.hasOwnProperty.call(c,a)&&"e"!==a&&Object.defineProperty(n,a,o(a));return n.e=function(e){function t(){_--,"prepare"===x&&(A[e]||i(e),0===_&&0===E&&s())}return"ready"===x&&r("prepare")

插件03 HtmlWebpackPlugin

1.简单介绍

作用: 用得最多的地方是自动生成入口文件dist/index.html
插件网址: https://webpack.js.org/plugins/html-webpack-plugin/
安装: cnpm i -D html-webpack-plugin
默认生成文件dist/index.html内容如下

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

2.配置

// 参考 https://github.com/jantimon/html-webpack-plugin#configuration
...
const HtmlWebpackPlugin = require('html-webpack-plugin')
...
new HtmlWebpackPlugin({
    title: 'hello,零和壹在线课堂', // html5文件中<title>部分
    
    // 关键点1: 生成的文件完整名是什么?是放在哪个文件夹下?
    // 完整路径是 output.path+ filename
    
    filename: 'front.html', // 默认是index.html,服务器中设置的首页是index.html,如果这里改成其它名字,那么devServer.index改为和它一样
    
    // 关键点2: 在哪里找模板文件, 是 context+template是最后模板的完整路径,./不能少,path.resolve(context, template)
    template: './template/daqi.html', // 如果觉得插件默认生成的hmtl5文件不合要求,可以指定一个模板,模板文件如果不存在,会报错,默认是在项目根目录下找模板文件,才模板为样板,将打包的js文件注入到body结尾处
    inject:'body', // true|body|head|false,四种值,默认为true,true和body相同,是将js注入到body结束标签前,head将打包的js文件放在head结束前,false是不注入,这时得要手工在html中加js
            
})
// 关键明白2点:在哪里找模板文件,生成的html5文件又是放在哪里
// 模板文件位置: context+template
// 生成html5文件位置: output.path+filename

插件04 ExtractTextWebpackPlugin

介绍

作用: 从bundle中提取文本,单独存一个文件,最常用的是将css单独放在一个文件中,当style样式比较大时,这个办法比较好,会加快很多,因为样式和js可以同时请求
安装: D:\03www2018\study\webpack2018>cnpm i -D extract-text-webpack-plugin
官方文档: https://webpack.js.org/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"),
  ]
}

new ExtractTextPlugin的参数,如果是一个字符串,表示提取后生成的css文件名,当webpack-dev-server开启时,是在内存中

插件05 CopyWebpackPlugin

介绍

作用: 文件拷贝
安装: 根目录>cnpm i -D copy-webpack-plugin
官方文档: https://webpack.js.org/plugins/copy-webpack-plugin/

配置

const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
  plugins: [
    new CopyWebpackPlugin([
    
//from    定义要拷贝的源目录           from: __dirname + '/src/public'
//to      定义要拷贝到的目标目录     to: __dirname + '/dist'
//toType  file 或者 dir         可选,默认是文件
//force   强制覆盖先前的插件           可选 默认false
//context                         可选 默认base context可用specific context
//flatten 只拷贝文件不管文件夹      默认是false
//ignore  忽略拷贝指定的文件           可以用模糊匹配
            // {output}/file.txt
            { from: 'from/file.txt' },

            // equivalent
            'from/file.txt',

            // {output}/to/file.txt
            { from: 'from/file.txt', to: 'to/file.txt' },

            // {output}/to/directory/file.txt
            { from: 'from/file.txt', to: 'to/directory' },

            // Copy directory contents to {output}/
            { from: 'from/directory' },

            // Copy directory contents to {output}/to/directory/
            { from: 'from/directory', to: 'to/directory' },

            // Copy glob results to /absolute/path/
            { from: 'from/directory/**/*', to: '/absolute/path' },

            // Copy glob results (with dot files) to /absolute/path/
            {
                from: {
                    glob:'from/directory/**/*',
                    dot: true
                },
                to: '/absolute/path'
            },

            // Copy glob results, relative to context
            {
                context: 'from/directory',
                from: '**/*',
                to: '/absolute/path'
            },

            // {output}/file/without/extension
            {
                from: 'path/to/file.txt',
                to: 'file/without/extension',
                toType: 'file'
            },

            // {output}/directory/with/extension.ext/file.txt
            {
                from: 'path/to/file.txt',
                to: 'directory/with/extension.ext',
                toType: 'dir'
            },

            // Ignore some files using glob in nested directory
            {
                from: 'from/directory',
                to: 'to/directory',
                ignore: ['nested/**/*.extension']
            }
        ], {
            ignore: [
                // Doesn't copy any files with a txt extension    
                '*.txt',

                // Doesn't copy any file, even if they start with a dot
                '**/*',

                // Doesn't copy any file, except if they start with a dot
                { glob: '**/*', dot: false }
            ],

            // By default, we only copy modified files during
            // a watch or webpack-dev-server build. Setting this
            // to `true` copies all files.
            copyUnmodified: true
        })
  ]
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值