What is the Loader?

Let’s take a look at the official Webpack documentation:

Loader(file-loader) Packages related configurations

Let’s take a look at the file to package. I want to package this JS file, but WebPack does not recognize the JPG file introduced. We need to introduce a file-loader to help Webpack recognize JPG files:



[name][hash][ext]
[name]: indicates the name of the original file. [hash] : indicates the hash value of the content. [ext] : indicates the extension name of the original file



webpack --config webpack.config.js



file-loader
webpack --config webpack.config.js
file-loader

url-loader

Url-loader is similar to file-loader, except that url-loader can convert packaged files into Base64 encoding and place them into generated files.

Url-loader configuration in Webpack:

limit:204800

Css-loader, style-loader, Sas-loader, and post-loader

The loader is executed from left to right and from top to bottom. Css-loader: helps clarify the relationship between CSS files and finally merges them into a single PIECE of CSS code. Style-loader: After getting the combined CSS code, it will put the code in the HEAD tag of the HTML page. Sass-loader: compiles SASS to CSS. Post-loader: Adds the CSS compiled by Sass to the browser manufacturer prefix using the autoprefix plug-in. The CSS-Loader has a local scope attribute modules as shown:



Create a createAvatar.js file and an avatar. SCSS file

import avatar from './avatar.jpg';

function createAvatar() {
  var img = new Image();
  img.src = avatar;
  img.classList.add("avatar")
  var root = document.getElementById('root');
  root.append(img);
}

export default createAvatar
Copy the code

.avatar {
  width: 150px;
  height: 150px;
  transform: translate(100px,100px);
}


Copy the code

Import createAvatar.js to the index.js file

import avatar from './avatar.jpg';
import style from './index.scss';
import createAvatar from './createAvatar.js'

createAvatar() 

var img = new Image();
img.src = avatar;
img.classList.add(style.avatar)
var root = document.getElementById('root');
root.append(img);
Copy the code

Create two images on the page, one of which is added to the class by img.classlist.add (“avatar”), The other is img.classlist.add (style.avatar), which introduces the CSS Module so that only the image has the avatar class name. This prevents CSS from taking effect globally.