Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack loaders vs plugins; what's the difference?

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.

like image 348
Tim Perkins Avatar asked May 26 '16 05:05

Tim Perkins


People also ask

What is the use of plugins in webpack?

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.

What is loaders in webpack?

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.

Why do you need a webpack loader?

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.

How do loaders work webpack?

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)


2 Answers

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 -

enter image description here References: Article and Image

like image 80
WitVault Avatar answered Sep 20 '22 11:09

WitVault


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.

like image 38
helt Avatar answered Sep 18 '22 11:09

helt