Exploring the role of CSS loader and style loader



Everyone knows they’re using itwebpackIt is used when building front-end projectssass-loader、less-loader、postcss-loader、css-loader、style-loader, but theseloaderWhat role does it play? This article mainly expoundscss-loaderAndstyle-loaderThe role and Realization ofloaderUnderstanding.


css-loaderYes@importandurl()Process, likejsanalysisimport/require()Similarly, an array is generated by default to store the processed style string and export it.

Suppose there are three style files:a.module.scssb.module.scssc.module.scss, the dependencies between them are as follows:

// a.module.scss
@import './b.module.scss';

.container {
  width: 200px;
  height: 200px;
  background-color: antiquewhite;

// b.module.scss
@import url('./c.module.scss');

.text {
  font-size: 16px;
  color: #da2227;
  font-weight: bold;

// c.module.scss
.name {
  font-size: 16px;;
  color: #da7777;
  font-weight: bold;

stayindex.jsxIntroduce them into the file

// index.jsx
import React from 'react';

import styles from './a.module.scss';

const Index = () => {
  return <div className={styles.container}>
    <span className={styles.text}><span className={styles.name}>xxx,</span>hello world!!!</span>

export default Index;

webpack.config.jsBuild script

// webpack.config.js
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const webpack = require('webpack');

module.exports = {
  entry: {
    index: './src/index.jsx'
  output: {
    filename: 'js/[name].js',
    path: path.resolve(__dirname, './dist'),
    library: 'MyComponent',
    libraryTarget: 'umd',
  resolve: {
    extensions: ['.js', '.jsx', '.tsx'],
  module: {
    rules: [
        test: /\.(js|jsx)$/, 
        exclude: /node_modules/, 
        loader: "babel-loader" 
        test: /\.(sa|sc|c)ss$/,
        use: [
            loader: 'css-loader',
            options: {
              Modules: false, // CSS modules are prohibited
        test: /\.(jpg|jpeg|png|gif)$/, 
        use: ['url-loader'] 
  plugins: [
    new webpack.ProgressPlugin(),
    new CleanWebpackPlugin({
      cleanOnceBeforeBuildPatterns: ['dist']

.babelrcto configure

// .babelrc
  "presets": [
  "plugins": [

staypackage.jsonConfigure build commands"build:dev": "webpack --mode none"。 To facilitate the analysis of the built code, heremodeSet tonone

Three kindsmodeMethod:

development WillDefinePlugininprocess.env.NODE_ENVThe value of is set todevelopment。 Enable valid names for modules and chunks, that is, replace the module ID with the module name.
Exploring the role of CSS loader and style loader

Exploring the role of CSS loader and style loader

production WillDefinePlugininprocess.env.NODE_ENVThe value of is set toproduction
Enable deterministic for modules and chunksConfused nameFlagDependencyUsagePlugin
Exploring the role of CSS loader and style loader
none Do not use any default optimization options

implementyarn build:devBuild and analyze the generated files

(1)a.module.scssuse@importIntroducedb.module.scss, processed intoSame moduleArray of___CSS_LOADER_EXPORT___Import and export

Exploring the role of CSS loader and style loader

(2)b.module.scssuse@import url()Introducedc.module.scss, butc.module.scssAn array that is processed separately and placed in another module___CSS_LOADER_EXPORT___Import and export

Exploring the role of CSS loader and style loader

(3)a.module.scssAndb.module.scssIs processed into an array of modules,c.module.scssAn array that is processed separately into another module, butb.module.scssAndc.module.scssThe relationship is introduced by. How does this relate to dependencies after construction?

a.module.scssAndb.module.scssProcessed into modulesidby12An array of,c.module.scssProcessed into modulesidby15Array of modulesidby12Module imported from moduleidby15And append it to the moduleidby12In the array of, the last unified is the array__WEBPACK_DEFAULT_EXPORT__Export,css-loaderAt this point, the process is over

in additioncss-loaderIt also provides other functions, such ascss modules, you can refer to the example for detailscss modulesConstruction and its principle are not introduced here

Exploring the role of CSS loader and style loader

Exploring the role of CSS loader and style loader

css-loaderExport mode

As mentioned above, the imported styles are converted into style strings and put into the module array. This is the default processing method. In fact, there are two other methods.

Configuration itemexportTypeAllow export styles to'array''string'perhaps'css-style-sheet'Constructable style(i.eCSSStyleSheet), default:'array'

CSSStyleSheetInterface represents aCSSStyle sheet and allows you to review and edit the list of rules in the style sheet. It is from the parent typeStyleSheetInherit properties and methods.

OneCSSA style sheet contains a set of rules that represent rulesCSSRuleObject. EachCSSRules can be operated through the objects associated with them. These rules are contained inCSSRuleListInside, you can use thecssRules (en-US)Property get.

For example,CSSStyleRuleA rule in an object may contain such a style:

h1, h2 {
  font-size: 16pt;


style-loaderThe function of is toCSSInsert intoDOMIn, it is processingcss-loaderThe exported module array, and then pass the style throughstyleInsert labels or other forms intoDOMYes.

Configuration iteminjectTypeConfigurable handlestylesInsert intoDOMThe main methods are:

  • styleTag: by using multiple<style></style>Automatic handlestylesInsert intoDOMYes. This method is the default behavior
  • singletonStyleTag: by using a<style></style>To automaticallystylesInsert intoDOMin
  • autoStyleTag: andstyleTagSame, but when the code is inIE6-9When running in, opensingletonStyleTagpattern
  • lazyStyleTag: use multiple when needed<style></style>holdstylesInsert intoDOMYes. recommendlazy styleFollow use.lazy.cssNaming conventions as suffixes,style-loaderThe basic usage is to use.cssAs a file suffix (the same is true for other files, such as:.lazy.lessand.less)。 When usedlazyStyleTagWhen,style-loaderInsert the inert into thestyles, when neededstylesCan passstyle.use() / style.unuse()sendstyleAvailable.
  • lazySingletonStyleTag: by using a<style></style>To automaticallystylesInsert intoDOMProvide inert support as above
  • lazyAutoStyleTag: andlazyStyleTagSame, but when the code is inIE6-9When running in, openlazySingletonStyleTagpattern
  • linkTag: use multiple<link rel="stylesheet" href="path/to/file.css">Insert styles into the dom. thisloaderWill be used at run time JavaScript dynamicGround insertion<link href="path/to/file.css" rel="stylesheet">。 wantstatic stateinsert<link href="path/to/file.css" rel="stylesheet">Please useMiniCssExtractPlugin

We takestyleTagAnalysis by inserting:

All styles mentioned above are appended to the moduleidby12In the module array, get the module firstidby12Module array, and then generatestyleLabel insert its styleDOMin

Exploring the role of CSS loader and style loader

In the figure above_node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default()The result is returned by the module in the figure belowupdateMethod, which calls many other methods to pass the style throughstyleLabel insertionDOM

Exploring the role of CSS loader and style loader

reference resources:



Recommended Today

Proper memory alignment in go language

problem type Part1 struct { a bool b int32 c int8 d int64 e byte } Before we start, I want you to calculatePart1What is the total occupancy size? func main() { fmt.Printf(“bool size: %d\n”, unsafe.Sizeof(bool(true))) fmt.Printf(“int32 size: %d\n”, unsafe.Sizeof(int32(0))) fmt.Printf(“int8 size: %d\n”, unsafe.Sizeof(int8(0))) fmt.Printf(“int64 size: %d\n”, unsafe.Sizeof(int64(0))) fmt.Printf(“byte size: %d\n”, unsafe.Sizeof(byte(0))) fmt.Printf(“string size: %d\n”, […]