基础配置
module.exports = {
//入口
entry: {
header:'./header.js'
},
//输出
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
},
//模块
module: {
rules: [
{
test: /\.txt$/,
use: 'raw-loader'
}
]
},
//插件
plugins: []
};
插件
clean-webpack-plugin
说明:清除
使用:
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
plugins: [
new CleanWebpackPlugin(),
]
}
ProvidePlugin
说明:自动加载模块,而不必到处 import 或 require 。
使用:
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
CopyWebpackPlugin:
说明:将单个文件或整个目录复制到构建目录
使用:
new CopyWebpackPlugin([{
from:"//web//index.html",
to:"./index.html"
}])
ReplaceInFileWebpackPlugin
说明:替换文件里的内容
插件工作原理
一个插件结构如下:
module.exports class MyExampleWebpackPlugin() {
//构造函数
constructor(options){
}
//定义一个 `apply` 方法
apply(compiler) {
// 指定一个挂载到 webpack 自身的事件钩子。
compiler.plugin('webpacksEventHook', function(compilation, callback) {
console.log("This is an example plugin!!!");
callback();
});
};
};
插件工作原理:
- 初始化MyExampleWebpackPlugin,获得一个实例
- 初始化compiler对象后调用MyExampleWebpackPlugin.apply(compiler)
- 插件实例可以通过compiler.plugin(事件名称,回调函数)监听webpack广播的事件,并通过compiler对象操作Webpack
Webpack原理
概念
Tapable:事件流机制
compiler:构建块
compilation:一次构建过程
参考资料:
webpack中文文档:https://www.webpackjs.com/concepts/