Share 12 commonly used Loaders in Webpack (Summary)

Share 12 commonly used Loaders in Webpack (Summary)

Preface

Original intention: To organize some commonly used loaders and share them with everyone, so that you can know which loader to use in which scenario. If there are any big guys out there who know how to just swipe left quietly, please don't criticize me if you don't like it.
Suitable for: Junior front-end developers.

style-loader

Purpose: Used to mount the compiled CSS style to the page style tag. You need to pay attention to the order in which loaders are executed. The style-loader is placed first because loaders are executed from bottom to top. Finally, all the compilations are completed and mounted on the style for installation.

cnpm i style-loader -D

Configuration
webpack.config.js

module.exports = {
 module: {
  rules:
   {
    test: /\.css/,
    use: ["style-loader"]
   }
  ]
 }
}

css-loader

Purpose: Used to identify .css files. To process css, it must be used together with style-loader. If only css-loader is installed, the style will not take effect.
Install

cnpm i css-loader style-loader -D

Configuration
webpack.config.js

module.exports = {
 module: {
  rules:
   {
    test: /\.css/,
    use: [
     "style-loader",
     "css-loader"
    ]
   }
  ]
 }
}

sass-loader

Purpose: CSS preprocessor, which we often use in project development. It is very convenient to write CSS, in one word: "awesome".
Install

cnpm i [email protected] node-sass -D

Configuration
index.js

import "index.scss"

index.scss
body {
 font-size: 18px;
 background: red;
}

webpack.config.js

module.exports = {
 module: {
  rules:
   {
    test: /\.scss$/,
    use: [
     "style-loader",
     "css-loader",
     "sass-loader"
    ],
    include: /src/, 
   },
  ]
 }
}

postcss-loader

Purpose: Used to supplement various browser kernel prefixes for CSS styles. It is very convenient and we don’t need to write them manually.
Install

cnpm i postcss-loader autoprefixer -D

Configuration
postcss.config.js

If you don't write it in the file, you can also write it in the options of postcss-loader. Writing it in the file is the same as writing it there.

module.exports = {
 plugins: [
  require("autoprefixer")({
   overrideBrowserslist: ["> 1%", "last 3 versions", "ie 8"]
  })
 ]
}

property describe
> 1% The browser used by more than 1% of the world's population
> 5% in CN Specified country usage coverage
last 2 versions All browsers are compatible up to the last two versions as tracked by CanIUse.com
Firefox ESR The latest version of Firefox
Firefox > 20 Specify a browser version range
not ie <=8 Direction excludes some versions
Firefox 12.1 Specify the browser compatibility to the specified version

webpack.config.js

module.exports = {
 module: {
  rules:
   {
    test: /\.scss$/,
    use: [
     "style-loader",
     "css-loader",
     "sass-loader",
    "postcss-loader"
    ],
    include: /src/, 
   },
  ]
 }
}

babel-loader

Purpose: Convert Es6+ syntax to Es5 syntax.
Install

cnpm i babel-loader @babel/core @babel/preset-env -D
  • babel-loader This is a module that makes babel and webpack work together
  • @bable/core This is the core module of the babel compiler
  • @babel/preset-env This is the presetter officially recommended by Babel, which can automatically add the required plugins and patches to compile Es6 code according to the user's environment

Configuration
webpack.config.js

module.exports = {
 module: {
  rules:
   {
    test: /\.js$/,
    use: {
     loader: "babel-loader",
     options:
      presets: [
       ['@babel/preset-env', { targets: "defaults"}]
      ]
     }
    }
   },
  ]
 }
}

ts-loader

Purpose: Used to configure project typescript
Install

cnpm i ts-loader typescript -D

Configuration
webpack.config.js
The current configuration of ts-loader will not take effect, it will only compile and recognize .ts files. The main configuration file is in tsconfig.json

module.exports = {
 module: {
  rules:
   {
    test: /\.ts$/,
    use: "ts-loader"
   },
  ]
 }
}

tsconfig.json

{
 "compilerOptions": {
  "declaration": true,
  "declarationMap": true, // Enable map file debugging "sourceMap": true,
  "target": "es5", // Convert to Es5 syntax}
} 

webpack.config.js

module.exports = {
 entry: "./src/index.ts",
 output: {
  path: __dirname + "/dist",
  filename: "index.js",
 },
 module: {
  rules:
   {
    {
     test: /\.ts$/,
     use: "ts-loader",
    }
   }
  ]
 }
}

html-loader

Purpose: Sometimes we want to import a html page code snippet and assign it to the DOM element content. In this case, html-loader is used.
Install

It is recommended to install a lower version, as higher versions may be incompatible and cause errors. I installed the 0.5.5 version configuration here
index.js

import Content from "../template.html"

document.body.innerHTML = Content

webpack.config.js
module.exports = {
 module: {
  rules:
   {
    test: /\.html$/,
    use: "html-loader"
   }
  ]
 }
}

file-loader

Purpose: Used to process file type resources, such as jpg, png and other images. The return value is based on publicPath.
Install

cnpm i file-loader -D

Configuration
index.js

import img from "./pic.png"
console.log(img) // https://www.baidu.com/pic_600eca23.png

webpack.config.js

module.exports = {
 module: {
  rules:
   {
    test: /\.(png|jpg|jpeg)$/,
    use: [
     {
      loader: "file-loader",
      options:
       name: "[name]_[hash:8].[ext]",
       publicPath: "https://www.baidu.com" 
      }
     }
    ]
   }
  ]
 }
}

url-loader

Purpose: url-loader also processes image type resources, but it is a little different from file-loader. url-loader can set a different operation based on the image size. If the image size is larger than the specified size, the image will be packaged as a resource, otherwise the image will be converted into a base64 string and merged into the js file for installation.

cnpm i url-loader -D

Configuration
index.js

import img from "./pic.png"

webpack.config.js

module.exports = {
 module: {
  rules:
   {
    test: /\.(png|jpg|jpeg)$/,
    use: [
     {
      loader: "url-loader",
      options:
       name: "[name]_[hash:8].[ext]",
       limit: 10240, // The unit here is (b) 10240 => 10kb
       // If it is less than 10kb, it will be converted to base64 and packaged into the js file. If it is larger than 10kb, it will be packaged into the dist directory.}
     }
    ]
   }
  ]
 }
}

html-withimg-loader

Purpose: When we compile images, we use file-loader and url-loader. These two loaders search for related image resources in js files, but files in html will not be searched. So we want to package the images in html as well. In this case, we use html-withimg-loader
Install

cnpm i html-withimg-loader -D

Configuration
index.html

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Home</title>
</head>
<body>
 <h4>I am a frogman</h4>
 <img src="./src/img/pic.jpg" alt="">
</body>
</html>

webpack.config.js
If the src path of img appears as [Object Module] during packaging, the solution is

  • Downgrade file-loader to 4.2.0
  • Modify the options parameter esModule to false
module.exports = {
 module: {
  rules:
   {
    test: /\.(png|jpg|jpeg)$/,
    use: {
     loader: "file-loader",
     options:
      name: "[name]_[hash:8].[ext]",
      publicPath: "http://www.baidu.com",
      esModule: false
     }
    }
   },
   {
    test: /\.(png|jpeg|jpg)/,
    use: "html-withimg-loader"
   }
  ]
 }
}

vue-loader

Purpose: Used to compile .vue files. If we build our own vue project, we can use vue-loader. Let's take a brief look at it below. I won't go into details here.
Install

cnpm i [email protected] vue vue-template-compiler -D
  • vue-loader is used to identify .vue files
  • vue Needless to say, recognition supports vue syntax
  • vue-template-compiler syntax template rendering engine {{}} template, script, style

Configuration
main.js

import App from "./index.vue"
import Vue from 'Vue'
new Vue({
 el: "#app",
 render: h => h(App) 
})

index.vue

<template>
 <div class="index">
 {{ msg }}
 </div>
</template>

<script>
export default {
 name: 'index',
 data() {
 return {
  msg: "hello frogman"
 }
 },
 created() {},
 components: {},
 watch: {},
 methods: {}
}
</script>
<style scoped>

</style>

webpack.config.js

const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
 entry: "./src/main.js",
 output: {
  path: __dirname + "/dist",
  filename: "index.js",
 },
 module: {
  rules:
   {
    test: /\.vue$/,
    use: "vue-loader"
   }
  ]
 },
 plugins: [
  new VueLoaderPlugin()
 ]
}

eslint-loader

Purpose: Used to check whether the code complies with the specifications and whether there are any syntax errors.
Install

cnpm i eslint-loader eslint -D

Configuration
index.ts

var abc:any = 123;
console.log(abc)

.eslintrc.js
Here are a few simple rules

module.exports = {
 root: true, 
 env: {
  browser: true,
 },
 rules:
  "no-alert": 0, // Disable alert
  "indent": [2, 4], // indentation style "no-unused-vars": "error" // variable declarations must use }
}

webpack.config.js

module.exports = {
 module: {
  rules:
   {
    test: /\.ts$/,
    use: ["eslint-loader", "ts-loader"],
    enforce: "pre",
    exclude: /node_modules/
   },
   {
    test: /\.ts$/,
    use: "ts-loader",
    exclude: /node_modules/
   }
  ]
 }
}

Summarize

This is the end of this article about sharing 12 commonly used Loaders in Webpack (summary). For more relevant content about commonly used Loaders in Webpack, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Tutorial on using css-loader and less-loader in Webpack
  • Detailed explanation of webpack's scss and postcss-loader configuration
  • Detailed explanation of Webpack loader file-loader
  • Webpack implements a loader example of converting inline style px to vw
  • Detailed explanation of webpack loader and plugin writing
  • How to configure postcss-loader in webpack2.0
  • A detailed explanation of webpack custom loader
  • Webpack3 loader full analysis

<<:  Windows keeps remote desktop from being automatically disconnected for a long time

>>:  MySQL encryption and decryption examples

Recommend

Detailed explanation of client configuration for vue3+electron12+dll development

Table of contents Modify the repository source st...

How to make spaces have the same width in IE and FF?

body{font-size:12px; font-family:"宋体";}...

Detailed explanation of MySQL EXPLAIN output columns

1. Introduction The EXPLAIN statement provides in...

Ubuntu 20.04 how to modify the IP address example

illustrate: Today, when continuing the last offic...

HTML Tutorial: Unordered List

<br />Original text: http://andymao.com/andy...

How to Apply for Web Design Jobs

<br />Hello everyone! It’s my honor to chat ...

Summary of naming conventions for HTML and CSS

CSS naming rules header: header Content: content/c...

Summary of the Differences between SQL and NoSQL

Main differences: 1. Type SQL databases are prima...

Record the whole process of MySQL master-slave configuration based on Linux

mysql master-slave configuration 1. Preparation H...

MySQL configuration master-slave server (one master and multiple slaves)

Table of contents Ideas Host Configuration Modify...

Index in MySQL

Preface Let's get straight to the point. The ...