插件 | Plugins

插件(Plugins)

插件是webpack 的支柱。webpack本身是建立在您在webpack配置中使用的相同插件系统上的!

剖析

ConsoleLogOnBuildWebpackPlugin.js

function ConsoleLogOnBuildWebpackPlugin() { }; ConsoleLogOnBuildWebpackPlugin.prototype.apply = function(compiler) { compiler.plugin('run', function(compiler, callback) { console.log("The webpack build process is starting!!!" callback( } };

作为一个聪明的JavaScript开发人员,您可能还记得这个Function.prototype.apply方法。由于这种方法,你可以将任何函数作为插件传递(this将指向compiler)。您可以使用此样式在配置中内联自定义插件。

用法

配置

webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin' //installed via npm const webpack = require('webpack' //to access built-in plugins const path = require('path' const config = { entry: './path/to/my/entry/file.js', output: { filename: 'my-first-webpack.bundle.js', path: path.resolve(__dirname, 'dist') }, module: { rules: [ { test: /\.(js|jsx)$/, use: 'babel-loader' } ] }, plugins: [ new webpack.optimize.UglifyJsPlugin(), new HtmlWebpackPlugin{template: './src/index.html'}) ] }; module.exports = config;

Node API

即便使用 Node API,用户也应该在配置中传入 plugins 属性。compiler.apply 并不是推荐的使用方式。

some-node-script.js

const webpack = require('webpack' //to access webpack runtime const configuration = require('./webpack.config.js' let compiler = webpack(configuration compiler.apply(new webpack.ProgressPlugin() compiler.run(function(err, stats) { // ... }

你知道吗:上面看到的例子与webpack运行时本身非常相似隐藏在webpack源代码中的很多很好的用法示例可以应用到您自己的配置和脚本中