preface
Everyone knows they’re using itwebpack
It is used when building front-end projectssass-loader、less-loader、postcss-loader、css-loader、style-loader
, but theseloader
What role does it play? This article mainly expoundscss-loader
Andstyle-loader
The role and Realization ofloader
Understanding.
css-loader
css-loader
Yes@import
andurl()
Process, likejs
analysisimport/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.scss
,b.module.scss
,c.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.jsx
Introduce 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>
</div>
}
export default Index;
webpack.config.js
Build 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: [
'style-loader',
{
loader: 'css-loader',
options: {
Modules: false, // CSS modules are prohibited
}
},
'sass-loader'
]
},
{
test: /\.(jpg|jpeg|png|gif)$/,
use: ['url-loader']
}
]
},
plugins: [
new webpack.ProgressPlugin(),
new CleanWebpackPlugin({
cleanOnceBeforeBuildPatterns: ['dist']
}),
],
}
.babelrc
to configure
// .babelrc
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
],
"plugins": [
"@babel/plugin-proposal-class-properties"
]
}
staypackage.json
Configure build commands"build:dev": "webpack --mode none"
。 To facilitate the analysis of the built code, heremode
Set tonone
。
Three kindsmode
Method:
development |
WillDefinePlugin inprocess.env.NODE_ENV The value of is set todevelopment 。 Enable valid names for modules and chunks, that is, replace the module ID with the module name.![]() |
---|---|
production |
WillDefinePlugin inprocess.env.NODE_ENV The value of is set toproduction 。Enable deterministic for modules and chunksConfused name, FlagDependencyUsagePlugin ,FlagIncludedChunksPlugin ,ModuleConcatenationPlugin ,NoEmitOnErrorsPlugin andTerserPlugin 。![]() |
none |
Do not use any default optimization options |
implementyarn build:dev
Build and analyze the generated files
(1)a.module.scss
use@import
Introducedb.module.scss
, processed intoSame moduleArray of___CSS_LOADER_EXPORT___
Import and export
(2)b.module.scss
use@import url()
Introducedc.module.scss
, butc.module.scss
An array that is processed separately and placed in another module___CSS_LOADER_EXPORT___
Import and export
(3)a.module.scss
Andb.module.scss
Is processed into an array of modules,c.module.scss
An array that is processed separately into another module, butb.module.scss
Andc.module.scss
The relationship is introduced by. How does this relate to dependencies after construction?
a.module.scss
Andb.module.scss
Processed into modulesid
by12
An array of,c.module.scss
Processed into modulesid
by15
Array of modulesid
by12
Module imported from moduleid
by15
And append it to the moduleid
by12
In the array of, the last unified is the array__WEBPACK_DEFAULT_EXPORT__
Export,css-loader
At this point, the process is over。
in addition
css-loader
It also provides other functions, such ascss modules
, you can refer to the example for detailscss modules
Construction and its principle are not introduced here
css-loader
Export 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 itemexportType
Allow export styles to'array'
、'string'
perhaps'css-style-sheet'
Constructable style(i.eCSSStyleSheet
), default:'array'
CSSStyleSheet
Interface represents aCSSStyle sheet and allows you to review and edit the list of rules in the style sheet. It is from the parent typeStyleSheet
Inherit properties and methods.
OneCSS
A style sheet contains a set of rules that represent rulesCSSRule
Object. EachCSS
Rules can be operated through the objects associated with them. These rules are contained inCSSRuleList
Inside, you can use thecssRules
(en-US)Property get.
For example,CSSStyleRule
A rule in an object may contain such a style:
h1, h2 {
font-size: 16pt;
}
style-loader
style-loader
The function of is toCSS
Insert intoDOM
In, it is processingcss-loader
The exported module array, and then pass the style throughstyle
Insert labels or other forms intoDOM
Yes.
Configuration iteminjectType
Configurable handlestyles
Insert intoDOM
The main methods are:
styleTag
: by using multiple<style></style>
Automatic handlestyles
Insert intoDOM
Yes. This method is the default behaviorsingletonStyleTag
: by using a<style></style>
To automaticallystyles
Insert intoDOM
inautoStyleTag
: andstyleTag
Same, but when the code is inIE6-9
When running in, opensingletonStyleTag
patternlazyStyleTag
: use multiple when needed<style></style>
holdstyles
Insert intoDOM
Yes. recommendlazy style
Follow use.lazy.css
Naming conventions as suffixes,style-loader
The basic usage is to use.css
As a file suffix (the same is true for other files, such as:.lazy.less
and.less
)。 When usedlazyStyleTag
When,style-loader
Insert the inert into thestyles
, when neededstyles
Can passstyle.use()
/style.unuse()
sendstyle
Available.lazySingletonStyleTag
: by using a<style></style>
To automaticallystyles
Insert intoDOM
Provide inert support as abovelazyAutoStyleTag
: andlazyStyleTag
Same, but when the code is inIE6-9
When running in, openlazySingletonStyleTag
patternlinkTag
: use multiple<link rel="stylesheet" href="path/to/file.css">
Insert styles into the dom. thisloader
Will be used at run timeJavaScript
dynamicGround insertion<link href="path/to/file.css" rel="stylesheet">
。 wantstatic stateinsert<link href="path/to/file.css" rel="stylesheet">
Please useMiniCssExtractPlugin。
We takestyleTag
Analysis by inserting:
All styles mentioned above are appended to the moduleid
by12
In the module array, get the module firstid
by12
Module array, and then generatestyle
Label insert its styleDOM
in
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 belowupdate
Method, which calls many other methods to pass the style throughstyle
Label insertionDOM
reference resources: