# webpack 中 plugin 的作用是什么,有没有自己写过
Issue
欢迎在 Gtihub Issue 中回答此问题: Issue 76 (opens new window)
Author
loaders 的作用是转换其他类型的语言到 JS 语言, plugins 可以做其他所有 loaders 做不了的事情, 比如:
- bundle optimization(bundle 优化)
- assets management(assets 管理)
- injection of environment variables(注入环境变量)
- etc.
实际上 plugins 是 webpack 的基石, webpack 就是在 plugin system 上建立起来的.
为了使用 plugins, 我们需要 require() 并将它加入 plugins 数组.
// webpack.config.js
const HtmlWebpackPlugin = require("html-webpack-plugin");
const webpack = require("webpack"); //to access built-in plugins
module.exports = {
module: {
rules: [{ test: /\.txt$/, use: "raw-loader" }],
},
plugins: [new HtmlWebpackPlugin({ template: "./src/index.html" })],
};
在上面的例子中, html-webpack-plugin为我们的应用程序生成了一个 html 文件并自动注入所有生成的 bundle.
webpack 提供的 plugin 列表 (opens new window)
reference: webpack 官方文档 (opens new window)