所有的webpack内置插件都做为webpack静态属性存在,使用下面方式可以创建一个插件对象

  1. const webpack=require('webpack');
  2. new webpack.插件名(options)

DefinePlugin

全局常量定义插件,使用插件通常定义一些常量值,例如:

  1. new webpack.DefinePlugin({
  2. PI:`Math.PI`, //PI=Math.PI
  3. VERSION:`"1.0.0"`,//VERSION="1.0.0"
  4. DOMAIN:JSON.stringfy('duyi.com') //两种书写方式,`"duyi.ocom"`
  5. })

这样一来,在源码中,我们就可以直接使用插件中提供的常量,当webpack编译的完成以后,会自动替换为常量的值

BannerPlugin

它可以为每个chunk生成的头部文件添加一行注释,一般用于添加作者,公司,版权等信息

  1. new webpack.BannerPlugin({
  2. banner:`
  3. hash:[hash]
  4. chunkhash:[chunkhash]
  5. name:[name]
  6. autor:蓝瞳
  7. corporation:蓝瞳版权`
  8. })

ProviderPlugin

自动加载模块,不必到处 import 或者 require,在所有的模块中都可以使用 $ 调用jquery方法,_调用lodash方法

  1. new webpack.ProviderPlugin({
  2. $:'jquery',
  3. _:'lodash'
  4. })

综合配置

  1. const webpack = require('webpack');
  2. module.exports = {
  3. mode: 'development',
  4. plugins: [
  5. new webpack.DefinePlugin({
  6. PI: `Math.PI`, //PI=Math.PI
  7. VERSION: `"1.0.0"`,//VERSION="1.0.0"
  8. DOMAIN: JSON.stringify('duyi.com') //两种书写方式,`"duyi.ocom"`
  9. }),
  10. new webpack.BannerPlugin({
  11. banner: `
  12. hash:[hash]
  13. chunkhash:[chunkhash]
  14. name:[name]
  15. autor:蓝瞳
  16. corporation:蓝瞳版权`
  17. }),
  18. new webpack.ProvidePlugin({
  19. $: 'jquery',
  20. _: 'lodash'
  21. })
  22. ],
  23. }

代码

  1. console.log('PI', PI, 'version', VERSION, 'DOMAIN', DOMAIN);
  2. console.log('=================>')
  3. console.log($('item'));
  4. console.log(_.drop()[1, 2, 3], 2)