What is the difference between loaders and plugins in webpack?
The documentation for plugins just says:
Use plugins to add functionality typically related to bundles in webpack.
I know that babel uses a loader for jsx/es2015 transforms, but it looks like other common tasks (copy-webpack-plugin, for example) use plugins instead.
A webpack plugin is a JavaScript object that has an apply method. This apply method is called by the webpack compiler, giving access to the entire compilation lifecycle.
Loaders are transformations that are applied to the source code of a module. They allow you to pre-process files as you import or “load” them. Thus, loaders are kind of like “tasks” in other build tools and provide a powerful way to handle front-end build steps.
Webpack enables use of loaders to preprocess files. This allows you to bundle any static resource way beyond JavaScript. You can easily write your own loaders using Node. js.
The idea behind Webpack loaders is to provide multiple ways to handle some resource or asset - whether that's a javascript module, a CSS stylesheet, or an image. The loader is responsible for parsing/processing the resource, which might do any of the following: Transpile it into another language (e.g. babel-loader)
Adding complementary and simpler answer.
Loaders:
Loaders work at the individual file level during or before the bundle is generated.
Plugins:
Plugins work at bundle or chunk level and usually work at the end of the bundle generation process. Plugins can also modify how the bundles themselves are created. Plugins have more powerful control than loaders.
Just for an example you can clearly see in below image where loaders are working and where plugins are working -
References: Article and Image
Loaders do the pre-processing transformation of virtually any file format when you use sth like require("my-loader!./my-awesome-module")
in your code. Compared to plugins, they are quite simple as they (a) expose only one single function to webpack and (b) are not able to influence the actual build process.
Plugins on the other hand can deeply integrate into webpack because they can register hooks within webpacks build system and access (and modify) the compiler, and how it works, as well as the compilation. Therefore, they are more powerful, but also harder to maintain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With