Plugins(插件)1
Plugins是webpack的支柱。Webpack本身也是建立在和你的webpack配置使用的相同的插件系统上!
剖析
一个webpack plugin就是有apply
属性的JavaScript对象。Webpack编译器会调用这个apply
属性,使其能够访问整个编译生命周期。
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
方法。因为这个方法你可以传递任意函数为plugin(this
将会指向compiler
)。你可以用这个方式来内联自定义plugin到你的配置中。
用法
由于plugins可以接受参数/选项,你必须传递一个new
的实例给webpack配置中的plugins
属性。
有几种方式来使用plugins,要看你是怎么使用webpack。
Configuration(配置)
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)$/,
loader: 'babel-loader'
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin(),
new HtmlWebpackPlugin({template: './src/index.html'})
]
};
module.exports = config;
Node API
[TODO] 即使使用Node API,用户应当通过配置中的
plugins
属性传递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 runtime本身!有很多优秀的使用案例隐藏在webpack源代码中,你可以应用到你自己的配置和脚本里面!
1. https://webpack.js.org/concepts/plugins/ ↩