An easy-to-understand complete guide to loaders in Webpack 5

An easy-to-understand complete guide to loaders in Webpack 5

Webpack allows you to import lots of different stuff into your JavaScript code. This is possible due to a couple of great features that Webpack provides. We know that Asset Modules allow us to import images, fonts, or plain text files.

In case, one doesn't know about Asset Modules in Webpack, then check out my article - A complete guide to asset modules in Webpack.

In this article, we are going to talk about Webpack loaders.

??What is a Webpack loader?

Loaders allow you to import all other kinds of files that you can't handle using Asset Modules. Webpack was designed to help you bundle all your dependencies into one or more files. What kind of dependencies are we talking about? Usually, dependencies are other JavaScript modules that your main JavaScript file requires in order to do its job.

But we can do more than that! With Webpack, you can import CSS files right into your JavaScript code, you can import SASS, LESS, handlebars, XML and so much more! There are a lot of things you can import using Webpack. And Webpack loaders are JavaScript libraries that help you import all that stuff.

??Handling CSS With Webpack

One of the coolest features of Webpack is the ability to import CSS files right into your JavaScript code. Well, frankly speaking, we can import lots of different stuff into our JavaScript code and we already know how to import images with asset modules.

So why is it so cool to import CSS? Because with these modern component-based frameworks like React or the latest versions of Angular, it has become a best practice to separate your web application into many isolated components. Each component has its own behavior described by JavaScript and its own styles described by CSS. It's much better when component styles and behavior are in the same place. Then it's much easier to fix the box, add new features, and reuse such components.

Example: To demonstrate this, let’s create a button within JavaScript, and on the click on this button, render a paragraph element with the text “hello world”.

I’m going to adopt the above-said approach. I’ll create a folder named components, which is going to hold the button component hello-world-button.

No alt text provided for this image

Inside this folder, there’s a JS file that holds the code for the button component and its functionality.

No alt text provided for this image

and a CSS file that holds the stylings for that button component.

No alt text provided for this image

Now it’s time to import the class HelloWorldButton in the main JavaScript file index.js and instantiate it. Then invoke the render method on it.

No alt text provided for this image

Finally, building the component is finished. As you can guess, Webpack doesn't know yet how to import CSS, so let's teach Webpack how to do it. We need to go to the Webpack configuration file and create a new rule there.

This rule is going to affect all CSS files. If you remember, when we are talking about asset modules, we use a property named type. For loaders, we are going to use another property which is called use.

No alt text provided for this image

Here, we can specify one or more loaders that will be used to import our files. As you can see, we can not only use different loaders with Webpack, but we can also combine multiple loaders inside a single rule. This rule tells Webpack that every time it tries to import a CSS file, it needs to use both the css-loader and style-loader.

??Fact: Webpack processes loaders from right to left.

  1. css-loader: The CSS loader reads the contents of the CSS file and converts it into JavaScript representation, but it doesn't do anything else with this CSS.
  2. style-loader: Then the style loader takes the CSS and injects it into the page using style tags. By the way, using style loader bundles your CSS together with your JavaScript into a single resulting file called the bundle.js

When we were using Asset Modules, we didn't have to install any additional NPM packages because Webpack includes asset modules out of the box. On the other hand, when using loaders, we need to install them explicitly. Every Webpack loader comes as an NPM package that you can add as a dependency to your application.

In this case, we need to install two additional NPM packages, the css-loader, and style-loader.

npm install css-loader style-loader --save-dev        

Once the installation is finished, run the Webpack from the terminal to build the bundle. Now open the main index.html file in the browser and see the CSS is getting loaded for the button.

No alt text provided for this image

You would be able to see that the style-loader creates a style tag inside the head tag of the HTML page that holds the same styles we have written in the hello-word-button.css file.

No alt text provided for this image

So it seems everything works. Congratulations. we have successfully imported CSS into our JavaScript code and learned how to combine multiple loaders inside a single room.

??Handling CSS Preprocessor

We can also write our styles using SASS or LESS as well as other CSS processors. I will show you how to import SASS in this article, but you can easily use anything you want in your applications.

So let's change our hello-word-button.css into hello-word-button.scss and then I will use some variables for font size and colors.

No alt text provided for this image

Don't forget to change the import statement on the corresponding JavaScript file using it.

No alt text provided for this image

Now we need to create a rule for SCSS files.

No alt text provided for this image

Pay attention to the order in which all orders appear in the array. Webpack processes loaders from right to left.

  1. sass-loader: First, Webpack will invoke sass-loader, which will convert our SCSS code to CSS.
  2. css-loader: Then it will invoke CSS loader, which will take that converted CSS and convert it to the JavaScript representation.
  3. style-loader: only then Webpack will invoke style-loader, which will create style text inside our HTML page and put CSS into it.

Since we are using a new loader, we have to install it.

npm install sass-loader sass --save-dev        

Here I am installing sass-loader together with dart-sass Library.

There are multiple implementations of SASS and you can choose which one you would like to use in your applications. DART SASS is the primary implementation of SASS, which means it gets new features before any other implementation. It's fast, easy to install and it compiles to pure JavaScript, which makes it easy to integrate into modern web development workflows. It allows you to compile CSS files into CSS files at incredible speed.

Now let's run the Webpack again and go to the browser and check if everything still works. Refresh my page now and make several clicks.

No alt text provided for this image

Yes, it still works.

??Using the latest JavaScript features with Babel

In this section, we are going to learn how to import all the JavaScript files inside our JavaScript file. What you would say I already know how to import JavaScript files. You don't need any additional loader for that. And you're right, we actually already did that. We imported the class HelloWorldButton from hello-world-button.js, inside the index.js file and everything worked out of the box.

??So why do we need an additional loader like Babel?

JavaScript language is based on ECMAScript specification, and this specification is evolving all the time. Every time a new version of ECMAScript specification comes out, browsers go ahead and implement all the new features introduced in that version.

However, it takes quite some time to implement all those features in every browser. On the other hand, you and I would like to use these new features right away. We are not going to wait for a couple of years until all major browsers add support for those features.

So what should we do in this kind of situation? Luckily there are special tools that can help you start using those features right away so you don't need to wait anymore. These tools can convert modern JavaScript code into older JavaScript code that is already supported by all major browsers.

In this section, if you are going to use one of those very helpful tools. The tool we are going to use is called Babel. Babel is the most popular JavaScript compiler. It's used in almost every modern JavaScript application and here you will learn how you can use it together with Webpack.

Example: For demonstration purposes, we want to use?a pipeline operator?(|>) in our code, which is one of the non-standard JavaScript features.

So I wrote some code using the pipeline operator and paste it inside the main JS file index.js.

No alt text provided for this image

To make sure that the pipeline operator is not currently part of the JavaScript language, we run the Webpack.

No alt text provided for this image

As you can see, Webpack throws an error. It also says you may need an appropriate loader to handle this file type. And Webpack is right. Even though the pipeline operator is not part of the official script specification, you can still use them with Webpack.

We just need to use a special loader for that, which is called babel-loader. Let's create a new rule for JavaScript files inside our Webpack configuration.

No alt text provided for this image

Let’s understand all of these codes one by one. The exclude property allows this rule to be applicable to all JavaScript files except those located inside the node_modules folder.

I will tell Webpack to use Babel loader for these files. We also need to specify a couple of extra options for the babel-loader. In fact, we can specify extra options for any Webpack loader. Of course, this loader should support those options.

  1. presets: We need a special Babel preset, which is called envy. envy preset compiles an ES6, ES7, ES8, ES9, ES10, etc. down toES5. In other words, the envy preset supports the latest JavaScript standard defined in the latest script specification.
  2. @babel/plugin-proposal-pipeline-operator: As I already said earlier, the pipeline operator is not part of the official script specification, so we need a special Babel plugin to support this feature. This Babel plugin is called @babel/plugin-proposal-pipeline-operator. If you want to use another modern JavaScript feature that is not supported by major browsers yet, you should find a Babel plugin for that and add it to the list of plugins, you can use as many Babel plugins as you want.

Now the configuration is done, finally, we need to install the libraries we mentioned in the Webpack configuration file.

npm install @babel/core babel-loader @babel/preset-env @babel/plugin-proposal-pipeline-operator        

If I run Webpack now, it will use Babel loader when importing JavaScript files. And if it happens that our application uses some of the cutting-edge features that didn't make it to the current script specification. the current script specification.

This time our build works fine. Let's go to the browser now and check if everything still works as expected.

No alt text provided for this image

Congratulations! You've got the hang of Webpack loaders. No more struggling to figure out the ins and outs. You've got it all down.??

??As you may have noticed, we used the Babel plugin @babel/plugin-proposal-pipeline-operator to enhance the capabilities of the babel-loader. There are also numerous webpack plugins that can perform tasks beyond the scope of a loader, which I will discuss in my upcoming article. Stay tuned for more information.

Israa Salameh

Software Engineer at An-Najah National University Hospital (NNUH), AI/ML Master Student in NNU

7 个月

great article, I was looking for article like this ! I have two questions: 1. how to configure RTL css with webpack , also 2. If I have js code added in the html template by script tag how to make webpack bundle it ?

Jozsef Kerekes

Frontend Developer | CSS, Javascript, React & Typescript

1 年

Cool article, thanks

Arnab Mitra

Junior Research Fellow in mathematics at NISER Bhubaneswar ? Former Data Science intern at iNeuron.ai | Computer Vision | NLP | Machine Learning | Mathematics

2 年

Love this

要查看或添加评论,请登录

??Prasenjit Sutradhar的更多文章

社区洞察

其他会员也浏览了