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.
Loaders transform file types (right-to-left execution); Plugins hook into the broader build lifecycle — rule of thumb: need to transform a file → loader; need to hook into the build process → plugin.
- Loaders transform file types into modules — they operate at the file level within the module resolution pipeline.
- Execution order: right-to-left (bottom-to-top in the config array) — for example ['style-loader', 'css-loader', 'sass-loader'] runs sass-loader first.
- Common loaders: babel-loader (ES6+/JSX→ES5), css-loader (parses @import and url()), style-loader (injects CSS into the DOM), sass-loader (SCSS→CSS), file-loader/asset modules (handles images/fonts), ts-loader/swc-loader (TypeScript).
- A custom loader is a function that receives a source string, transforms it, and returns a new string — simple to implement.
- Plugins intervene in the Webpack compiler lifecycle via hooks (beforeRun, emit, done).
- Common plugins: HtmlWebpackPlugin (generates HTML with injected script tags), MiniCssExtractPlugin (extracts CSS into separate files instead of injecting into JS), TerserPlugin (minifies JS), DefinePlugin (replaces constants at build time — NODE_ENV), BundleAnalyzerPlugin (visualizes the bundle).
- Custom plugins are more complex than loaders: must implement an apply(compiler) method and tap into compiler hooks.
- Rule of thumb: need to transform a file type → loader; need to intervene in the build process more broadly → plugin.