Plugins
文档地址
Plugins是webpack的基础,jwebpack本身就是基于plugin system构建的。
使用的plugin system同构建普通app的plugin system形同。
plugin 提供一些loader
无法实现的功能
剖析
webpack plugin是包含apply属性的Javascript 对象。
webpack compiler会调用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();
});
};
使用
Function.prototype.apply
方法可以将任何function作为插件(this
指向compiler
对象)。可以使用该特性自定义plugins。
Usage
由于plugins可以接受argument/options,所以需要在webpack配置中传递通过new
关键字创建的plugin
对象。
配置
webpack.config.js配置文件的方式
配置为array对象。
如下:
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;
当多个bundles都是用一个通用的以来,CommonsChunkPlugin
可以将依赖代码抽取出来。
plugins: [
new webpack.optimize.CommonsChunkPlugin({
...
})
]
比较复杂的配置示例如下
// importing plugins that do not come by default in webpack
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var DashboardPlugin = require('webpack-dashboard/plugin');
// adding plugins to your configuration
plugins: [
// build optimization plugins
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: 'vendor-[hash].min.js',
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
drop_console: false,
}
}),
new ExtractTextPlugin({
filename: 'build.min.css',
allChunks: true,
}),
new webpack.IgnorePlugin(/^\.\/locale$/, [/moment$/]),
// compile time plugins
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"',
}),
// webpack-dev-server enhancement plugins
new DashboardPlugin(),
new webpack.HotModuleReplacementPlugin(),
]
Node API的形式
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) {
// ...
});