插件是webpack的支柱功能;目的在于解决loader无法实现的其他事情;
1:源码分析:
webpack插件是一个具有apply属性的JS对象。apply属性会被webpack compiler调用,并且compiler对象在整个编译生命周期访问
function ConsoleLogOnBuildWebpackPlugin() {
};
ConsoleLogOnBuildWebpackPlugin.prototype.apply = function(compiler) {
compiler.plugin('run', function(compiler, callback) {
console.log("webpack 构建过程开始!!!");
callback();
});
};
2:2种使用方法:
(1)在plungins属性中传入new实例
//webpack.config.js
cponst HtmlWebpackPlugin=require('html-webapck-plugin');
const webpack=require('webpack');
const path=require('path');
const config={
entry:'./path/to/my/entry/fils.js',
output:{
path:path.resolve(_dirname,'dist'),
filename:'my-first-webpack.bundle.js'
},
module:{
rules:[
{
test:/\.text/,
use:'raw-loader'
}
]
},
plugins:[
new webpack.optimize.UglifyJsPlugin(),
new HtmlWebpackPlugin({
template:'./src/index.html'
})
]
}
module.exports=config;
(2)Node API(不推荐)
//some-node-script.js
const webpack = require('webpack'); //访问 webpack 运行时(runtime)
const configuration = require('./webpack.config.js');
let compiler = webpack(configuration);
compiler.apply(new webpack.ProgressPlugin());
compiler.run(function(err, stats) {
// ...
});