The previous article organized four configuration concepts for webPack configurations. This article will sort out the use of loader.

loader

Since my project is based on Vue family bucket and SASS, loader part will have a partial introduction of this aspect. For those who use TS, React family bucket and less, please find the corresponding loader.

When webpack a module, it will take the module to the Rules of the Module for matching. If the module is matched, the corresponding Loader will be used for parsing.

Because there are many Loaders, it is difficult to sort out, so I will sort out the instructions according to the Loaders required by different file modules in the project.

vue

We usually use the.vue file to develop vUE components in the vUe-based bucket project directory, so the.vue file module needs to be parsed separately. Vue itself has a loader dedicated to parsing.vue files

vue-loader

Vue -loader is a loader that specializes in parsing. Vue files. As the name implies, it only parses. Vue files. Because. Vue files typically have three parts: the template module, which is used to write the template language; One is the Script module, which writes the JS part of the component. One is the Style module, which writes the CSS part of the component. Template module is parsed through a plugin of Vue, script module and style module provide a custom loader for parsing.

Therefore, the loader configuration is relatively simple:

{
  module: {
    rules: [{test: /\.vue$/.use: 'vue-loader'}}}]Copy the code

javascript

Most of the code in our project is JS code, and now the JS standard has reached ES2020, many ES6 and above standards need to be compiled into ES5 to be used in various browsers, so in the Webpack package, we also need to parse the JS code in the project. This is where the babel-loader is needed.

babel-loader

When it comes to Babel, when we use it in WebPack, there are a lot of complicated ways to use it. Here is the content in the Module:

{
  module: {
    rules: [{test: /\.js$/.use: 'babel-loader'}}}]Copy the code

This configuration alone is not enough to complete parsing of JS code. In fact, if you use es6 or higher syntax in your code, you’ll need to use the. Babelrc configuration file. The configuration content of this configuration file can also be directly uninstalled in rules, but it is better to separate the configuration content from the rules.

In fact, the babel-loader used in this configuration calls @babel/core when parsing the code, and then @babel/core converts the code. The transformation process will tune the configuration in the. Babelrc configuration file.

I will cover the configuration in the. Babelrc file in detail in another article.

css

CSS is also a very important part of the project. My project uses SASS to develop CSS. Install the following loader:

sass-loader

Sass-loader is a loader used to parse the SASS syntax. To use this loader, install the Node-sass dependency package. This package is used to enable sass to compile on the Node side.

Installing Node-Sass is also a bit tricky. Because this package is designed for sass to compile on the Node side, the version requirements of sass are relatively high. Different versions of Sass have different node version ranges, which need to be selected according to your node environment. At the same time, the installation is not very smooth. General dependent packages can be downloaded and installed directly using NPM, while Node-Sass can easily fail to be downloaded directly using NPM, so it is necessary to consider changing the source of Taobao or using CNPM to install.

postcss-loader

Postcss-loader is a JS tool for converting CSS code, adapting CSS styles, and smoothing out differences. Because the kernel is different in different browsers, some styles are implemented differently in different browsers. Postcss-loader was invented to smooth out differences between browsers. This allows us to develop without having to worry about these issues. However, adding CSS styles is not actually implemented by the Loader itself, but by working with things like autoprefixer, postCSs-pxtorem, so it needs to be installed and configured. You can also create a postcss.config.js file. I’ll sort this out later.

css-loader

Css-loader is used to interpret @import and URL () and parse them after import/require(). Loader has a lot of configuration items, here because I only need to use the configuration item to importLoaders in my project, so I only introduce this one, other configuration items can be viewed on the webpack official website. ImportLoaders specifies the number of loaders to use before CSS-Loader. The configuration is as follows:

{
  test: /\.css$/.use: [
    'vue-style-loader'.'style-loader',
    {
      loader: 'css-loader'.// To compile @import and URL () and parse CSS
      options: {
        // The number of loaders to be applied before the loader, meaning that 'postcss-loader','sass-loader' is used when parsing CSS.
        // Because the incoming CSS file may be a Sass file
        'postcss-loader','sass-loader',' postcss-loader';
        importLoaders: 2}},'postcss-loader'.'sass-loader']},Copy the code

ImportLoaders = postCSs-loader; postCSs-loader = postCSs-loader; sass-loader = postCSs-loader; That is, the nearest number of Loaders to the right (below) of CSS-Loader.

style-loader

Style-loader inserts a

vue-style-loader

Vue-style-loader is used with vue-loader. Vue-style-loader is used to parse.vue files, but the three modules need to be parsed separately. Vue-style-loader is used to parse the style modules in.vue files. Vue-style-loader is developed from style-loaderfork and based on this loader, so it works the same as style-loader. However, there are also some differences. Support for SSR is added and some functions supported by style-loader are removed. Therefore, based on the needs of our project, we still need to use both of these two Loaders.

The CSS and SASS are packaged

Based on these loaders, we can configure sASS. For example, SASS needs to be converted to CSS by SCSS-Loader first, and then use postCSS-loader to add prefix and convert units, and then use CSS-Loader to process import/require() statements. These statements are processed using SCSS-loader and postCSS-loader according to the file type. Finally, the processed CSS code is inserted into the DOM by style-loader and vue-style-loader.

If you are packaging in a formal environment, instead of using style-loader, use the mini-CSs-extract-plugin with compressed CSS code.

{
  test: /\.css$/.use: [
    'vue-style-loader'.// It is used to compile the CSS part of the.vue file
    isDev ? 'style-loader' : MiniCssExtractPlugin.loader, // Use MiniCssExtractPlugin instead of style-loader
    {
      loader: 'css-loader'.// To compile @import and URL () and parse CSS
      options: {
        // The number of loaders to be applied before the loader, meaning that 'postcss-loader','sass-loader' is used when parsing CSS.
        // Because the incoming CSS file may be a Sass file
        'postcss-loader','sass-loader',' postcss-loader';
        importLoaders: 2}},'postcss-loader'.// Add declaration prefixes. Autoprefixer needs to be installed and configured in postcss.config.js
    'sass-loader' // Sass compiles. Node-sass dependencies need to be installed. CNPM is recommended for installing Node-sass] {},test: /\.scss$/.use: [
    'vue-style-loader',
    isDev ? 'style-loader' : MiniCssExtractPlugin.loader, 
    'css-loader'.'postcss-loader'.'sass-loader']},Copy the code

Other documents

The project usually needs to use files of other formats, such as WOFF, TTF, EOT and SVG for text ICONS, and JPG, JPEG, PNG, GIF, SVG and other formats for picture files. Generally we will consider using external links or local files in the form of introduction. Here, we mainly need to package and process local files, so we need to use the following loader.

file-loader

File-loader generates an MD5 hash of the file content by default and saves the hash as the file name in the package directory without changing the extension. File-loader also needs some configurations to be used. Here are a few: You can use [name](original file name),[ext](original extension),[hash](original hash value),[path](original path),[N](matching the NTH regex). PublicPath Specifies the path prefix to facilitate the use of the CDN. OutputPath Specifies the package directory.

url-loader

The url-loader function is similar to file-loader, but it has a feature that it can carry out different packaging processing according to the size of the file. For example, if the file size is smaller than a specific size, the package will return a DataURL format. For example, if an image is less than 10K, it will be directly converted to the DataURL package stored in the file of the call, so that there is no need to reference the file again. For online use, the client does not need to make an additional request for this small file. Of course, this requires the limit attribute to be configured.

Package configuration for other files

File-loader and URl-loader are different, and different loaders can be used according to different files. For example, font files can be directly used by file-loader, and image files can be classified by url-loader. Smaller images can be packaged directly into the file, and larger images can be packaged into the file.

{
  test: /\.(woff|ttf|eot|svg)$/.use: 'file-loader' // Used to parse files or external links imported through import/require()
},
{
  test: /\.(jpe? g|png|gif|svg)$/.use: {
    loader: 'url-loader'.// It is used to compile files to base64 format
    options: {
      name: "image/[contentHash].[ext]".ContentHash is the hash stamp of the image, and ext is the suffix
      limit: 100 * 1024.// Size limit
      esModule: false // Enable CommonJS module syntax}}}Copy the code

The next article will sort out the configuration of Babel and PostCSS-Loader.