Loaders transform file types (right-to-left execution); Plugins can thiệp vào build lifecycle rộng hơn — rule of thumb: cần transform file → loader; cần hook vào build process → plugin.
- Loaders transform file types thành modules — hoạt động ở file level trong module resolution pipeline.
- Execution order: right-to-left (bottom-to-top trong config array) — ví dụ ['style-loader', 'css-loader', 'sass-loader'] chạy sass-loader trước.
- Loaders phổ biến: babel-loader (ES6+/JSX→ES5), css-loader (parse @import và url()), style-loader (inject CSS vào DOM), sass-loader (SCSS→CSS), file-loader/asset modules (handle images/fonts), ts-loader/swc-loader (TypeScript).
- Custom loader là function nhận source string, transform, return new string — đơn giản implement.
- Plugins can thiệp vào Webpack compiler lifecycle qua hooks (beforeRun, emit, done).
- Plugins phổ biến: HtmlWebpackPlugin (generate HTML với injected script tags), MiniCssExtractPlugin (tách CSS thành files riêng thay vì inject vào JS), TerserPlugin (minify JS), DefinePlugin (thay constants lúc build — NODE_ENV), BundleAnalyzerPlugin (visualize bundle).
- Custom plugin phức tạp hơn loader: phải implement apply(compiler) method và tap vào compiler hooks.
- Rule of thumb: cần transform file type → loader; cần can thiệp vào build process rộng hơn → plugin.