Share 12 commonly used Loaders in Webpack

Preface

Original intention: sort out some commonly used loaders and share with you, so that you can know which loaders to use in which scenarios. If there are big guys who know how to slide left quietly, don't spray if you don't like it.

Suitable for the crowd: primary front-end development.

style-loader

Purpose: Used to cssmount the compiled style to the page stylelabel. Need to pay attention to the execution order of loader, style-loader is placed first, because loader is executed from bottom to top, and finally all compiled and mounted to style

installation

cnpm i style-loader -D

Configuration

webpack.config.js

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

css-loader

Purpose: It is used to identify .cssfiles, and the processing cssmust be style-loaderused together. Only the installation css-loaderstyle will not take effect.

installation

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, we often use in project development, it is cssvery convenient to write , one word "stick".

installation

cnpm i sass-loader@5.0.0 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: It is used to supplement various browser kernel prefixes of css style. It is too convenient, so we don't need to write it manually.

installation

cnpm i postcss-loader autoprefixer -D

Configuration

postcss.config.js

If you do not write it in the file, you can also write on postcss-loaderthe optionsinside, written in the file where it is written with the same

module.exports = {
    
    
    plugins: [
        require("autoprefixer")({
    
    
            overrideBrowserslist: ["> 1%", "last 3 versions", "ie 8"]
        })
    ]
}
Attributes description
> 1% A browser used by more than 1% of people worldwide
> 5% in CN Designated country usage coverage
last 2 versions All browsers are compatible to the last two versions according to the version tracked by CanIUse.com
Firefox ESR The latest version of Firefox
Firefox > 20 Specify the browser version range
not ie <=8 Directions exclude some versions
Firefox 12.1 The specified browser is compatible 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+ grammar to Es5 grammar.

installation

cnpm i babel-loader @babel/core @babel/preset-env -D
  • babel-loader This is the 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 pre-installer officially recommended by babel, which can automatically add the required plug-ins 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

installation

cnpm i ts-loader typescript -D

Configuration

webpack.config.js

The current configuration ts-loaderwill not take effect, but the recognition .tsfile will be compiled , and the main configuration file will be in tsconfig.jsonit

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

tsconfig.json

{
    
    
    "compilerOptions": {
    
    
      "declaration": true,
      "declarationMap": true, // 开启map文件调试使用
      "sourceMap": true,
      "target": "es5", // 转换为Es5语法
    }
}  

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 introduce a htmlpage code snippet assigned to the DOMcontent of the element, then we use ithtml-loader

installation

cnpm i html-loader@0.5.5 -D

It is recommended to install the lower version, the higher version may be incompatible and cause an error. I installed version 0.5.5 here

Configuration

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

Use: for handling file type resource, such as jpg, pngother image. The return value publicPathshall prevail.

installation

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: It url-loader is also processing image type resources, but it is file-loadera bit different. url-loaderYou can set a different operation according to 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 to a base64string Merge into jsfile

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, // 这里单位为(b) 10240 => 10kb
                            // 这里如果小于10kb则转换为base64打包进js文件,如果大于10kb则打包到dist目录
                        }
                    }
                ]
            }
        ]
    }
}

html-withimg-loader

Purpose: When we compile pictures, we use file-loaderand url-loader. Both of these loaderare to find jsrelated picture resources in htmlthe file , but the files inside will not be found. So we htmlalso want to pack the pictures in, then usehtml-withimg-loader

installation

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>首页</title>
</head>
<body>
    <h4>我蛙人</h4>
    <img src="./src/img/pic.jpg" alt="">
</body>
</html>

webpack.config.js

If the src path of img appears in the package [Object Module], 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"
            }
        ]
    }
}

view-loader

Purpose: It is used to compile .vuefiles. If we build our own vueproject, we can use it vue-loader. Let's briefly understand it, so I won't repeat it here.

installation

cnpm i vue-loader@15.7.0 vue vue-template-compiler -D
  • vue-loader is used to identify .vue files
  • Needless to say, vue 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 蛙人"
    }
  },
  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 conforms to the specification and whether there are grammatical errors.

installation

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, // 禁止使用alert
        "indent": [2, 4], // 缩进风格
        "no-unused-vars": "error" // 变量声明必须使用
    }
}

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/
            }
        ]
    }
}

thank

Thank you for reading this article. I hope it will be helpful to you. If you have any questions, please correct me.

I’m a frogman (✿◡‿◡), if you think it’s ok, please like it ❤.

Interested friends can join [Front-end entertainment circle exchange group] Welcome everyone to communicate and discuss

Writing is not easy, "Like" + "Watching" + "Repost" Thank you for your support❤

Good articles in the past

"Talk about using Decorator in Vue projects"

"Talk about what are CommonJs and Es Module and their difference"

"Map that takes you easily to understand the data structure"

"Do you know all the JavaScript tips used in these jobs?"

"[Recommended Collection] Share some commonly used Git commands in work and how to solve special problem scenarios"

"Do you really understand the features of ES6?

Guess you like

Origin blog.csdn.net/weixin_44165167/article/details/115072289