Table of contents
1. Configure the less environment
1. First install node: In cmd: node -v check whether node is installed
2. Install less: cnpm install -g less
3. Check whether less is installed successfully: lessc -v
4. After the installation is successful, create the xx.less file in the workspace
5. Compile less in the console, command: lessc style.less style.css
lessc + file name to be compiled + file name compiled into css
2. Use less directly in the browser
This method must run the project in server mode
It is not recommended to use it directly on the front end. It can be used on the server side.
Introduce the Less file in the project and parse the Less js file
LESS allows variables to be defined using the @ symbol. Variable assignment is done using colon (:).
The format of declaring variables in LESS is "@variable name: variable value"
Variables can be used first in the declaration
Pseudo selectors used with mixins
10.less_annotations and imports
Should variable names be separated by dashes or underscores?
8. Use selector inheritance to streamline CSS
2. Build a Webpack environment
3. Webpack adds configuration files
5. Use Loader_ to process Less files in Webpack
6. Use Loader_ to process Sass files in Webpack
7. Use plugin_HTML plugin in Webpack
8. Webpack separates CSS files
mini-css-extract-plugin conflicts with style-loader, style-loader needs to be deleted
9. Webpack compresses CSS files
10. Configure Babel in Webpack
Add configuration file "babel.config.js"
There are two ways to implement mode:
13. Configure the quick running plan
14. Separation of development mode and production mode
webpack configuration development mode and production mode
15. Devtool enhanced debugging process in Webpack
Best Practices for Source Maps
16. .browserslistrc file description
17.postcss-loader handles css compatibility
18.Webpack builds React environment
19.Webpack builds Vue environment
Add configuration (webpack.config.js)
21. Proxy proxy in Webpack (in fact, it is a cross-domain problem)
Install network request scheme
Specify document processing area
Check the file size, if it is too large, deal with it
24. Code inspection in JavaScript
25.Configuring ESLint in Webpack
webpack configuration file (webpack.dev.config.js)
Add a new .eslintrc.js file in the root directory
Install Airbnb rule dependencies
Using Airbnb in eslint configuration file
1. Less
1. Configure the less environment
1. First install node: In cmd: node -v check whether node is installed
node -v
2. Install less: cnpm install -g less
cnpm install -g less
3. Check whether less is installed successfully: lessc -v
lessc -v
4. After the installation is successful, create the xx.less file in the workspace
5. Compile less in the console, command: lessc style.less style.css
lessc + file name to be compiled + file name compiled into css
lessc style.less style.css
2. Use less directly in the browser
Kind tips
This method must run the project in server mode
It is not recommended to use it directly on the front end. It can be used on the server side.
// 1.先安装一个服务器
cnpm install -g http-server
// 2.运行方式:在当前目录终端下执行
http-server
// Available on:
// http://192.168.110.154:8080
// http://127.0.0.1:8080
// Hit CTRL-C to stop the server
Introduce the Less file in the project and parse the Less js file
<link rel="stylesheet/less" type="text/css" href="style.less" /> <script src="./less.min.js" ></script>
3.less_variable
LESS allows variables to be defined using the @ symbol. Variable assignment is done using a colon (:) .
The format of declaring variables in LESS is "@variable name: variable value"
@width: 1200px; @height: 300px; .container { width: @width; height: @height; background-color: #f1f1f1; }
Selector uses variables
Selector names can also be declared using variables
@my-selector: banner; .@{my-selector} { font-weight: bold; line-height: 40px; margin: 0 auto; }
Url address uses variables
@images: "../img"; body { color: #444; background: url("@{images}/hello.png"); }
Variables can be used first in the declaration
.container { width: @width; height: @height; background-color: #f1f1f1; } @width: 1200px; @height: 300px;
properties as variables
Properties are easily treated as variables using the $prop syntax. Sometimes this can make your code easier
.widget { color: #efefef; background-color: $color; margin: 15px; padding: $margin; font-size: 30px; left:$font-size; }
4.less_mix
Mixins allow you to use attributes of one class for another class and include the class name as its attribute
.p1 { color: red; } .p2 { background: #64d9c0; .p1(); } .p3 { background: #DAA520; .p1; } // p1后面的括号可以省略不写
Mixed parentheses
If you want to create a mixin, but you don't want the mixin to appear in your CSS, put parentheses after the mixin definition
.my-mixin { color: black; } .my-other-mixin() { background: white; } .class { .my-mixin(); .my-other-mixin(); }
used in mixing
!important
Use the !important keyword after the mixin call to mark all properties it inherits as !important
.foo (@bg: #f5f5f5; @color: #900) { background: @bg; color: @color; } .unimportant { .foo(); } .important { .foo() !important; }
Mixing with parameters
Blends can also accept parameters, which are variables passed to the selector block when blending
.border-radius(@radius,@color:red) { // 声明变量的后面加:属性值 ,代表默认的属性 border-radius: @radius; color: @color } #header { .border-radius(4px,blue); // 返回值就是4px blue } .button { .border-radius(6px); // 返回值:6px red }
5. less_nesting
Less provides the ability to use nesting instead of or in conjunction with cascading
<div class="header"> <div class="nav"> <ul> <li> <a href="#">首页</a> </li> </ul> </div> </div> // 使用less嵌套 .header{ width: 100%; height: 70px; background-color: #f1f1f1; .nav{ width: 1200px; margin: 20px auto; ul{ overflow: hidden; clear: both; li{ float: left; a{ font-size: 16px; color: #999; letter-spacing: 2px; } } } } } // 编码后等同于css中的:如下 .header { width: 100%; height: 70px; background-color: #f1f1f1; } .header .nav { width: 1200px; margin: 20px auto; } .header .nav ul { overflow: hidden; clear: both; } .header .nav ul li { float: left; } .header .nav ul li a { font-size: 16px; color: #999; letter-spacing: 2px; }
Pseudo selectors used with mixins
You can also use pseudo-selectors with mixins using this method. Overridden as a mixin (
&
representing the parent of the current selector)<div class="header"> <div class="nav"> <ul> <li> <a href="#">首页</a> </li> </ul> </div> </div> // 使用less嵌套 @width:1200px; .header{ width: 100%; height: 70px; background-color: #f1f1f1; .nav{ width: @width; margin: 20px auto; ul{ overflow: hidden; clear: both; li{ float: left; &:hover{ background-color:green; } a{ font-size: 16px; color: #999; letter-spacing: 2px; } } } } } // 编码后等同于css中的:如下 .header { width: 100%; height: 70px; background-color: #f1f1f1; } .header .nav { width: 1200px; margin: 20px auto; } .header .nav ul { overflow: hidden; clear: both; } .header .nav ul li { float: left; } .header .nav ul li:hover { background-color: aquamarine; } .header .nav ul li a { font-size: 16px; color: #999; letter-spacing: 2px; }
6. Less_ operation
Arithmetic operators
+
,-
,*
,/
can operate on any number, color, or variable. When possible, arithmetic operators perform unit conversions before addition, subtraction, or comparison. The result of the calculation is based on the unit type of the leftmost operand . Units are ignored if the unit conversion is invalid or meaninglessNote: In the division operation, the content of the operation needs to be placed in parentheses
@size: 14px; @widht:1000px; @color:#333333; @height:600px; a{ font-size: @size + 4; // 字体就成了18px } .nav{ width: @widht - 200; } p{ color: @color * 3; } .box{ height: (@height / 2); // 注意:除法的需要将运算的内容放到一个括号里 }
is equivalent to, as follows:
a { font-size: 18px; } .nav { width: 800px; } p { color: #999999; } .box { height: 300px; }
7. less_escaping
Escaping allows you to use any string as a property or variable value. Content of any
~"anything"
or form will be output as-is~'anything'
Practice escaping a media query
.box{ background-color: #af3131; } @max768:~"screen and (max-width:768px)"; @min768:~"screen and (min-width:768px) and (max-width:992px)"; @min992:~"screen and (min-width:992px) "; @media @max768 { .box1{ .box; } } @media @min768 { .box2{ background-color: blueviolet; } } @media @min992 { .box3{ background-color: greenyellow; } }
The effect after escaping is as follows:
.box { background-color: #af3131; } @media screen and (max-width:768px) { .box1 { background-color: #af3131; } } @media screen and (min-width:768px) and (max-width:992px) { .box2 { background-color: blueviolet; } } @media screen and (min-width:992px) { .box3 { background-color: greenyellow; } }
8.less_function
Less has a variety of built-in functions for converting colors, processing strings, arithmetic operations, and more. These functions are described in detail in the Less Functions Manual
Function manual address : https://lesscss.org/functions/
@width:0.6; .box1{ width: percentage(@width);// 转化成百分比:60%; } .box2{ height: ceil(96.8px);//向上取整:97px; } .box3{ width: floor(96.8px);// 向下取整:96px; }
9. less_scope
Scoping in Less is very similar to scoping in CSS. Variables and mixins are looked up locally first, and if not found, are inherited from the "parent" level scope
@width:200px; .box{ .nav{ @width: 100px; ul{ li{ a{ width: @width; // retutn 100px, } } } } } .box1{ .nav{ ul{ li{ width: @width; // return 200px;只能往父级寻找,不能往子级寻找 a{ @widht:100px; } } } } } .box2{ .nav{ ul{ li{ a{ width: @width; // retutn 300px,懒加载,也可以解释成先引用后声明; } @width:300px; } } } }
10.less_annotations and imports
Comment
Both block comments and line comments can be used
/* 一个块注释 * style comment! */ @var: red; // 这一行被注释掉了! @var: white; /* 注释块内容 */ @col :red; // 注释行内容 @wid:100px;
import
You can import a
.less
file, and all variables in this file can be used in full. If the imported file is.less
an extension, the extension can be omitted// style.less文件 @width:200px; @height:50px; @cor:green; .box{ width:@height; color: @cor; } // index.less文件 @import url("./style.less");// 引入的文件后缀名.less,后缀名可以省略 .box2{ width: @width; height: 500px; color: @cor; } // index.less文件中引入 style.less文件 : @import url() // 编译index.less文件后 .box { width: 50px; color: green; } .box2 { width: 200px; height: 500px; color: green; }
2. Sass
1.Sass environment setup
sass
Ruby
It is developed based on the language, sosass
Ruby needs to be installed before installation. (Note: Ruby comes with mac without installing Ruby!)
Install Ruby
After the installation is completed, you need to test whether the installation is successful. Run CMD
the following command:
ruby -v
// ruby 3.1.2p20
RubyGems
RubyGems is similar to npm in Nodejs
RubyGems has always been very difficult to access in China. We need to replace its source with domestic ones.
// 删除替换原gem源
gem sources --add https://gems.ruby-china.com/ --remove https://rubygems.org/
// 打印是否替换成功
gem sources -l
// https://gems.ruby-china.com/
sass installation
Ruby
It comes with a RubyGems
system called , which is used to install Ruby
software based on it. We can use this system to easily install Sass
andCompass
// 安装如下(如mac安装遇到权限问题需加 sudo gem install sass)
gem install sass
gem install compass
// 检测是否安装成功
sass -v // Ruby Sass 3.7.4
compass -v // Compass 1.0.3
2. Compile_sass
sass
There are many ways to compile, such as command line compilation mode, compilation softwarekoala
, engineering toolswebpack
, etc.Write Sass code
The suffix of the Sass file is
.scss
.box { width: 300px; height: 400px; &-title { height: 30px; line-height: 30px; } }
command line compilation
sass style.scss style.css
3. sass_variables
use variables
sass
An important feature that benefits people is the fact that itcss
introduces variables for . You can define reusablecss
attribute values as variables, and then refer to them by variable names without having to write this attribute value repeatedly. Or, for an attribute value that is only used once, you can give it an easy-to-understand variable name, so that people can know the purpose of this attribute value at a glance
sass
Use symbols to identify variables$
Such as
$highlight-color
and$sidebar-width
. Why choose$
symbols? Because it is easier to recognize, more beautiful, and has no other use in CSS, it will not causecss
conflicts with existing or future syntax .$public-width:1226px; .container{ width: 100%; } .container .nav{ width: $public-width; height: 50px; margin: 9px auto; } .computer{ width: $public-width; height: 390px; background-color: #e9e966; } .phone{ width: $public-width; height: 288px; background-color: #d6d; } // 编译后 .container { width: 100%; } .container .nav { width: 1226px; height: 50px; margin: 9px auto; } .computer { width: 1226px; height: 390px; background-color: #e9e966; } .phone { width: 1226px; height: 288px; background-color: #d6d; } /*# sourceMappingURL=style.css.map */
Should variable names be separated by dashes or underscores?
sass
The variable names in cancss
be the same as the attribute names and selector names in , including dashes and underscores. It all depends on personal preference$link-color: blue; a { color: $link_color; }
4.sass_nested
css
Writing selectors repeatedly is very annoying. If you want to write a large series of styles that point to the same block of the page, you often need to write the same style over and over again.ID
#content article h1 { color: #333 } #content article p { margin-bottom: 1.4em } #content aside { background-color: #EEE }
Situations like this
sass
allow you to write only once and make the style more readable. In Sass, you can nest rule blocks within rule blocks like a Russian doll. It will help you handle these nested rules duringsass
output to avoid repeated writing.css
#content { article { h1 { color: #333 } p { margin-bottom: 1.4em } } aside { background-color: #EEE } }
:hover
In most cases, this simple nesting is fine, but in some cases it is not, for example, if you want to immediately apply a similar pseudo-class inside the nested selector . To address this and other situations,sass
a special structure is provided&
article a { color: blue; &:hover { color: red } }
The actual combat is as follows:
$public_width:1200px; $public_color:#666; $public_background:greenyellow; // 嵌套 .header{ width: 100%; .nav{ width: $public_width; height: 50px; background-color: $public_background; ul{ overflow: hidden; clear: both; li{ float: left; &:hover{ background-color: $public_background; } a{ color: $public_color; } } } } } // 编译后 .header { width: 100%; } .header .nav { width: 1200px; height: 50px; background-color: greenyellow; } .header .nav ul { overflow: hidden; clear: both; } .header .nav ul li { float: left; } .header .nav ul li:hover { background-color: greenyellow; } .header .nav ul li a { color: #666; } /*# sourceMappingURL=style.css.map */
5. Import sass files
css
There is a particularly uncommon feature,@import
rules, which allow acss
file to import othercss
files. However, the consequence is that@import
the browser will download othercss
files only when it is executed, which causes the page to load very slowly.
sass
There is also a@import
rule , but the difference is thatsass
the@import
rulecss
imports the relevant files when the file is generated. This means that all related styles are grouped into the samecss
file without requiring additional download requests.The rules used do not need to specify the full name of the imported file
sass
.@import
You can omit.sass
or.scss
file suffixDefault variable value
Normally, when you declare a variable repeatedly, only the last declaration is valid and it overwrites the previous values.
$link-color: blue; $link-color: red; a { color: $link-color; // red }
!default
The function is to reduce the priority of the variable value to the lowest$link-color: blue; $link-color: red !default; a { color: $link-color; // blue }
Nested imports
Unlike native ones
css
, commandssass
are allowed to be written in rules@import
css
// aside.scss aside { background: blue; color: white; } // style.scss .blue-theme { width:300px; @import "aside.scss" } // 编译后 .blue-thems{ width:300px; .aside { background: blue; color: white; } }
6. Silent annotations
css
The functions of comments include helping you organize styles, allowing you to understand why you write it this way when you look at your code in the future, and providing simple style instructions. However, you don't want everyone who views your site's source code to see all comments.
sass
An additional comment syntax is provided that differs fromcss
the standard comment format/* ... */
, namely silent comments, whose content does not appear in the generatedcss
file. The syntax of silent comments is the same as that of single-line comments inJavaScript``Java
similar languages. They start with and continue to the end of the lineC
//
// style.sass /* 会出现在css样式文件中 */ // 静默注释:不会出现在css样式中 // style.css // 编译后 @charset "UTF-8"; /* 会出现在css样式文件中 */ /*# sourceMappingURL=style.css.map */
In fact, the content of comments within
css
the standard comment format/* ... */
can also be erased in the generatedcss
file.css
When comments appear in places that are not allowed natively , such as incss
attributes or selectors,sass
we do not know how to generate them tocss
the corresponding location in the corresponding file, so these comments are erased.// 这样写就不会出现在css样式中 body { color /* 这块注释内容不会出现在生成的css中 */: #333; }
The actual combat is as follows:
/* 会出现在css样式文件中 */ // 静默注释:不会出现在css样式中 .header{ background-color: greenyellow; /* 背景颜色*/ color/* 字体颜色*/: #666;// 这样就不会出现在css样式中 letter-spacing: 2px;// 字符间距 }
After compilation --->
@charset "UTF-8"; /* 会出现在css样式文件中 */ .header { background-color: greenyellow; /* 背景颜色*/ color: #666; letter-spacing: 2px; } /*# sourceMappingURL=style.css.map */
7. sass_mix
If you have several small styles that are similar throughout your website (such as consistent colors and fonts), it's a good idea to use variables to handle this situation uniformly. But when your styles become more and more complex, and you need to reuse large sections of style code, independent variables cannot cope with this situation. You can
sass
reuse large sections of styles through mixins@mixin rounded-corners { border-radius: 5px; } .notice { background-color: green; border: 2px solid #00aa00; @include rounded-corners; }
@mixin container { width: 100px; height: 50px; border: 1px solid #67e500; margin: 10px; } .root{ padding-left: 20px; box-shadow: 0 5px 10px #e5e5e5; @include container; } // 编译后 .root { padding-left: 20px; box-shadow: 0 5px 10px #e5e5e5; width: 100px; height: 50px; border: 1px solid #67e500; margin: 10px; } /*# sourceMappingURL=style.css.map */
mixed parameters
Mixing doesn't always have to produce the same style . The exact style a mixin generates can be customized by passing
@include
parameters to the mixin at time .In addition, we can also specify the default value of the parameter. When the parameter is not passed, the default value can be used
@mixin content ($width,$height,$color:rgb(248, 153, 11)) { width: $width; height: $height; background-color: cornflowerblue; color: $color; } .box{ margin: 10px; @include content(100px,256px ,#aecded) } .box2{ border: 1px solid #999; border-radius: 15px; @include content(145px,40px);// 颜色没有传值,会使用默认颜色 } // 编译后 .box { margin: 10px; width: 100px; height: 256px; background-color: cornflowerblue; color: #aecded; } .box2 { border: 1px solid #999; border-radius: 15px; width: 145px; height: 40px; background-color: cornflowerblue; color: #f8990b; } /*# sourceMappingURL=style.css.map */
8. Use selector inheritance to streamline CSS
When used
sass
, the last major feature that reduces duplication is selector inheritance. Selector inheritance means that one selector can inherit all styles defined for another selector.@extend
This is achieved through the syntaxWays to reduce code:
☛ Define variables;
☛ Mix;
☛Inheritance;
.container{ width: 1226px; height: 480px; box-shadow: 0 5px 10px #e5e5e5; margin-left: 27.7px; } .root{ padding-bottom: 23px; @extend .container; } .box{ float: left; text-align: center; @extend .container; } .login_pwd{ padding: 2px; letter-spacing: 3px; @extend .container; } // 编译后 .container, .root, .box, .login_pwd { width: 1226px; height: 480px; box-shadow: 0 5px 10px #e5e5e5; margin-left: 27.7px; } .root { padding-bottom: 23px; } .box { float: left; text-align: center; } .login_pwd { padding: 2px; letter-spacing: 3px; } /*# sourceMappingURL=style.css.map */
Inheritance principle
Generally using inheritance will make your application
css
nice and tidy. Because inheritance will onlycss
copy the selector when it is generated, not large sections ofcss
properties.
9.Sass_Operation
Sass supports addition, subtraction, multiplication, and division of numbers (
+, -, *, /
), and converts values between different units if necessary.Kind tips
During the calculation process, different units should not participate in the calculation.
$size:1000px; .root{ width: $size + 200px; }
$size:1000px; .root{ width: $size - 200px; }
$size:1000px; .root{ width: $size * 2; }
$size:1000px; .root{ width: ($size / 2); }
Priority in operations
Parentheses can be used to affect the order of operations
$size:1000px; .root{ width: ($size - 400) * 2; }
Application scenarios
During mobile terminal adaptation, there is usually REM calculation.
For example: the root
font-size
is50px
, the value given by the designer is340rem
$fontREM:50; .root{ width:(340rem / $fontREM); }
10.Control instructions
Sass provides some basic control instructions, such as referencing styles when certain conditions are met, or setting a range to repeat the output format. Control instructions are an advanced function that are not commonly used in daily writing.
@if
When
@if
the return value of the expression is notfalse
ornull
, the condition is true, and the code in the output{ }
p { @if 1+1==2 { border: 1px solid; } @if 5 < 3 { border: 2px dotted; } @if null { border: 3px double; } } // return border:1px solid;
@for
@for
The instruction can repeatedly output the format within a limited range, and each time the output result is changed according to the requirements (the value of the variable).@for $i from 1 through 3 { .item-#{$i} { width: 2px * $i; } } // return .item-1 { width: 2px; } .item-2 { width: 4px; } .item-3 { width: 6px; } /*# sourceMappingURL=style.css.map */
3. Webpack
1. Introduction to Webpack
Let’s think about a question: When front-end projects get bigger and bigger, can we continue to develop according to the previous way of thinking?
The crux of the problem: file management, ES6 code conversion, project packaging...
Solution: front-end engineering (Webpack)
Front-end engineering
In the development of enterprise-level front-end projects, standardize the tools, technologies, processes, and experiences required for front-end development.
For example:
Build a wall: As simple as it is, as long as you have all the materials ready, you can just do it alone
Building a building: It requires a lot of large machines and more people. The most important thing is to standardize the work to avoid dangers.
Essentially, webpack is a static module bundler for modern JavaScript applications. When webpack processes an application, it internally builds a dependency graph from one or more entry points and then combines every module required in your project into one or more bundles, which are static resources for show your content
2. Build the Webpack environment
install global
webpack
// 先判断有没有安装node.js node -v npm install --save [email protected] npm install --save [email protected]
Create a local project folder (you can use the command or create it in the code editor)
mkdir webpack_demo cd webpack_demo
Initialize the project
npm init
After executing the initialization project command, the following appears: (If you do not need to set it, you can directly press Enter to skip it)
Install
webpack
locallynpm install --save-dev [email protected] npm install --save-dev [email protected]
use
webpack
Create project structure: Create under the file path of webpack_demo
src
,public两个文件夹
// src/show.js export function show(content) { window.document.getElementById('root').innerText = 'Hello,' + content; }
// src/index.js import { show } from './show.js' show('iwen');
Excuting an order:
webpack
如果在终端执行webpack命令的时候出现以下情况:
Webpack-cli needs to be installed globally
// 安装全局webpack-cli npm install webpack-cli -g
If the above situation occurs, it means that webpack is packaged successfully, and the dist folder will appear in the project file path.
Kind tips
webpack will automatically look for the src directory, then look for the index.js entry file, then package it, and finally generate a dist directory as the packaged content.
public
Create underindex.html
and introduce automatically generatedmain.js
files<!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>Document</title> </head> <body> <div id="root"></div> <script src="../dist/main.js"></script> </body> </html>
3. Webpack adds configuration files
webpack
You can add configuration files, and after you have configuration files, you can operate them moreEntry configuration
Create
webpack.config.js
a file in the root directory of the project and enter the following codemodule.exports = { // JavaScript 执行入口文件 entry: './src/index.js', };
Exit configuration
webpack.config.js
Add export configuration code in the fileconst path = require("path"); module.exports = { // 配置入口文件 entry:"./src/index.js", // 配置出口文件 output:{ // 把所有依赖的模块合并输出到一个bundle.js文件 filename:"bundle.js", // 把输入的文件都放到dist目录下 // path.resolve:合并路径 path:path.resolve(__dirname,"./dist"), } }
Then we execute
webpack
the command , and it will be executed by default.webpack.config.js
It will run according to the configuration file.
4. Using Loader in Webpack
Webpack can only understand JavaScript and JSON files, which is the built-in capability of webpack available out of the box. The loader enables webpack to process other types of files (such as CSS type files, image types, etc.) and convert them into valid modules for use.
Webpack treats all files as modules, and CSS files are no exception, so if you want to package CSS, you need to install it.
css-loader 和 style-loader
Add CSS files
index.js
Introduce CSS files into the fileimport "../src/css/index.css"
Change setting
Modify
webpack.config.js
configuration fileconst path = require("path"); module.exports = { module:{ rules:[ // 解析css文件 { test:/\.css$/, use:['style-loader','css-loader'] } ] } }
Kind tips
style-loader
css-loader
There is a sequence of sum and must be written first and thenstyle-loader
written.
css-loader
Install
css-loader
npm install --save-dev [email protected]
Install
style-loader
npm install --save-dev [email protected]
5. Use Loader_ to process Less files in Webpack
Install
Kind tips:
Two packages, less and less-loader, need to be installed.
npm instal --save-dev [email protected] [email protected]
Change setting
Modify
webpack.config.js
configuration fileconst path = require('path'); module.exports = { module: { rules: [ // 解析less文件 { test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader'] } ] } };
Add
less
files to the projectimport "../src/css/style.less"
6. Use Loader_ to process Sass files in Webpack
I want webpack to package scss\sass file types
Install
Kind tips
Two packages, sass and sass-loader, need to be installed.
npm instal --save-dev [email protected] [email protected]
Change setting
Modify
webpack.config.js
configuration filemodule.exports = { module: { rules: [ // 解析sass文件 { test: /\.(scss|sass)$/, use: ['style-loader', 'css-loader', 'sass-loader'] } ] } };
Add
scss
files to the projectimport "../src/css/style.scss"
7. Use plugin_HTML plugin in Webpack
html-webpack-plugin
Can help ussrc
copyindex.html
a copy to the root directory of the projectInstall
npm install [email protected] --save-dev
Configure plugin
const HtmlPlugin = require('html-webpack-plugin') module.exports = { // 解析html文件 plugins: [ new HtmlPlugin({ template: './src/index.html', // 指定源文件的存放路径 filename: './index.html' // 指定生成的文件的存放路径 }) ] };
Kind tips
It will automatically put the packaged bundle.js into the bottom of index.html
8. Webpack separates CSS files
The current packaging is to package JavaScript and CSS into one file at the same time. If the CSS is small, it is actually advantageous, but if the CSS is large, then this file should be extracted separately.
We can separate CSS using
mini-css-extract-plugin
Install
npm install --save-dev [email protected]
Modify configuration file
const minicssextractPlugin = require("mini-css-extract-plugin") module.exports = { module:{ rules:[ // 解析css文件 { test:/\.css$/, use:[minicssextractPlugin.loader,'css-loader'] }, // 解析less文件 { test:/\.less$/, use:[minicssextractPlugin.loader,"css-loader","less-loader"] }, // 解析sass文件 { test:/\.(sass|scss)$/, use:[minicssextractPlugin.loader,"css-loader","sass-loader"] } ] }, plugins:[ // 分离CSS文件 new minicssextractPlugin({ filename:"./css/index.css" }) ] }
Kind tips
mini-css-extract-plugin
Conflicts with and needs to be deletedstyle-loader
style-loader
9.
Webpack compresses CSS files
The separated
mini-css-extract-plugin
CSS files have not undergone compression, so we need to compress them separately, how to do it?Install
optimize-css-assets-webpack-plugin
Compress CSS files bynpm/cnpm install --save-dev [email protected] // 我刚开始使用npm安装,报错了,但是使用cnpm就没事
Modify configuration file
const minicssextractPlugin = require("mini-css-extract-plugin") const optimizecssassetswebpackPlugin = require("optimize-css-assets-webpack-plugin") module.exports = { module:{ rules:[ // 解析css文件 { test:/\.css$/, use:[minicssextractPlugin.loader,'css-loader'] }, // 解析less文件 { test:/\.less$/, use:[minicssextractPlugin.loader,"css-loader","less-loader"] }, // 解析sass文件 { test:/\.(sass|scss)$/, use:[minicssextractPlugin.loader,"css-loader","sass-loader"] } ] }, plugins:[ // 分离CSS文件 new minicssextractPlugin({ filename:"./css/index.css" }), // 压缩CSS文件 new optimizecssassetswebpackPlugin() ] }
10. Configure Babel in Webpack
At this point, many friends may find a problem. Why does the ES6 code we write now run normally?
That's because we are currently using
Chrome
a browser, which supports it by default, but what if some browsers cannot support it?I need to
babel
compile usingInstall
npm install --save-dev @babel/[email protected] npm install --save-dev @babel/[email protected] npm install --save-dev [email protected]
Add configuration file "babel.config.js"
Configuration files added in the project root directory
babel.config.js
// babel.config.js module.exports = { presets: ['@babel/preset-env'] }
Modify configuration file
module: { rules: [ // 使用babel将ES6语法转化成ES5语法 { test:/\.js$/, use:['babel-loader'] }, ] }
11.Mode in Webpack
Provides
mode
configuration options that tell webpack to use the built-in optimizations for the appropriate mode.'none'| 'development' | 'production'
Options describe development Will set the value in DefinePlugin
. Enables valid names for modules and chunks.process.env.NODE_ENV
development
production will set the value DefinePlugin
in . Enable deterministic obfuscated names for modules and chunks, , , , and .process.env.NODE_ENV
production
FlagDependencyUsagePlugin
FlagIncludedChunksPlugin
ModuleConcatenationPlugin
NoEmitOnErrorsPlugin
TerserPlugin
none Do not use any default optimization options There are two ways to implement mode:
First: Just provide
mode
options in the configuration objectmodule.exports = { mode: 'development', };
The second type: Passed from CLI parameters (that is, specifying the mode in the command entered in the terminal)
webpack --mode=development
12.Using DevServer in Webpack
So far
webpack
it can basically be used normally, but in actual development you may need:
- Serve HTTP instead of using local file preview;
- Monitor file changes and automatically refresh the web page to achieve real-time preview;
- Supports Source Map to facilitate debugging.
For these, Webpack has taken care of it for you. Webpack natively supports points 2 and 3 above, and can also easily achieve point 1 when combined with the officially provided development tool DevServer. DevServer will start an HTTP server to serve web page requests, and will also help start Webpack, receive file change signals sent by Webpack, and automatically refresh the web page through the WebSocket protocol to achieve real-time preview.
Install server dependencies
npm install -g [email protected] npm install --save-dev [email protected] // 使用npm安装报错,改成cnpm就好了
Modify configuration file
const path = require('path'); module.exports = { devServer: { // 服务器打开目录 static: path.join(__dirname, 'public'), // 开启压缩 compress: true, // 设置端口 port: 9000, // 热更新 hot: true, // 自动打开浏览器 open: true, //使用 History 路由模式时,若404错误时被替代为 index.html historyApiFallback: true } };
const path = require("path"); const htmlPlugin = require("html-webpack-plugin") const minicssextractPlugin = require("mini-css-extract-plugin") const optimizecssassetswebpackPlugin = require("optimize-css-assets-webpack-plugin") module.exports = { // 开发模式:development 生产模式:production // mode:"development", // 配置入口文件 entry:"./src/index.js", // 配置出口文件 output:{ // 把所有依赖的模块合并输出到一个bundle.js文件 filename:"bundle.js", // 把输入的文件都放到dist目录下 // path.resolve:合并路径 path:path.resolve(__dirname,"./dist"), }, module:{ rules:[ // 解析css文件 { test:/\.css$/, use:[minicssextractPlugin.loader,'css-loader'] }, // 解析less文件 { test:/\.less$/, use:[minicssextractPlugin.loader,"css-loader","less-loader"] }, // 解析sass文件 { test:/\.(sass|scss)$/, use:[minicssextractPlugin.loader,"css-loader","sass-loader"] }, // 使用babel将ES6语法转化成ES5语法 { test:/\.js$/, use:["babel-loader"] } ] }, plugins:[ // 解析HTML文件 new htmlPlugin({ template:"./public/index.html",// 指定html文件存放路径 filename:"./index.html"// 指定生成文件存放的路径 }), // 分离CSS文件 new minicssextractPlugin({ filename:"./css/index.css" }), // 压缩CSS文件 new optimizecssassetswebpackPlugin() ], devServer:{ // 服务器打开目录 static:path.join(__dirname,"public"), // 压缩 compress:true, // 端口 port:9000, // 实时更新 hot:true, // 自动打开浏览器 open:true, // 使用history路由模式,若404报错时被代替为index.html historyApiFallback:true } }
How the server works
webpack serve
webpack-dev-server
Kind tips
When the configuration file is modified, hot update is not possible and the server needs to be restarted. Hot update only applies to the remaining code.
src
13. Configure the quick running plan
Configuring the quick running scheme can facilitate us to unify the running method, otherwise we need to remember more keywords such as:
webpack
,webpack serve
,webpack-dev-server
etc.amendment
Configure in
package.json
,scripts
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start":"webpack --mode=production", "dev":"webpack-dev-server --mode=development" },
Kind tips
If
package.json
it is not found in the file , you can regenerate the filescripts
by executingnpm init
package.json
Operation mode
npm start // 相当于运行webpack npm run dev // 相当于运行webpack serve
14. Separation of development mode and production mode
During the development process, we generally distinguish between development environments:
- development environment
- test environment
- Production Environment
- ...
development mode
Development mode exists to make development more convenient for developers. In development mode, it is generally for more convenient debugging, so the error message will be very comprehensive, and there is a hot update status, etc.
production mode
The production mode exists for project packaging and online launch. In the production mode, more error prompts will be removed to make the package as small as possible, etc.
webpack
Configure development mode and production modeIn
webpack
, we can distinguish between development mode and production mode, for example,mode
there isdevelopment
aproduction
difference betweenInstall dependencies:
webpack-merge
Can be used to merge multiple configuration files:npm install --save-dev [email protected] // npm安装报错,使用cnpm不报错
Create development and production schema files
Create and files in the project root directory
webpack.dev.config.js
webpack.prod.config.js
// webpack.dev.config.js 开发环境 const path = require("path") const {merge} = require("webpack-merge") const webpackConfig = require("./webpack.config") const devConfig = { mode:"production", devServer:{ // 服务器打开目录 static:path.join(__dirname,"public"), // 压缩 compress:true, // 端口 port:9000, // 实时更新 hot:true, // 自动打开浏览器 open:true, // 使用history路由模式,若404报错时被代替为index.html historyApiFallback:true } } module.exports = merge(webpackConfig,devConfig)
// webpack.prod.config.js 生产环境 const {merge} = require("webpack-merge") const webpackConfig = require("./webpack.config") const prodConfig = { mode:"production" } module.exports = merge(webpackConfig,prodConfig)
// webpack.config.js const path = require("path"); const htmlPlugin = require("html-webpack-plugin") const minicssextractPlugin = require("mini-css-extract-plugin") const optimizecssassetswebpackPlugin = require("optimize-css-assets-webpack-plugin") const webpackConfig = { // 开发模式:development 生产模式:production // mode:"development", // 配置入口文件 entry:"./src/index.js", // 配置出口文件 output:{ // 把所有依赖的模块合并输出到一个bundle.js文件 filename:"bundle.js", // 把输入的文件都放到dist目录下 // path.resolve:合并路径 path:path.resolve(__dirname,"./dist"), }, module:{ rules:[ // 解析css文件 { test:/\.css$/, use:[minicssextractPlugin.loader,'css-loader'] }, // 解析less文件 { test:/\.less$/, use:[minicssextractPlugin.loader,"css-loader","less-loader"] }, // 解析sass文件 { test:/\.(sass|scss)$/, use:[minicssextractPlugin.loader,"css-loader","sass-loader"] }, // 使用babel将ES6语法转化成ES5语法 { test:/\.js$/, use:["babel-loader"] } ] }, plugins:[ // 解析HTML文件 new htmlPlugin({ template:"./public/index.html",// 指定html文件存放路径 filename:"./index.html"// 指定生成文件存放的路径 }), // 分离CSS文件 new minicssextractPlugin({ filename:"./css/index.css" }), // 压缩CSS文件 new optimizecssassetswebpackPlugin() ], devServer:{ // 服务器打开目录 static:path.join(__dirname,"public"), // 压缩 compress:true, // 端口 port:9000, // 实时更新 hot:true, // 自动打开浏览器 open:true, // 使用history路由模式,若404报错时被代替为index.html historyApiFallback:true } } module.exports = webpackConfig;
Reconfigure the running mode: (in the package.json file)
"scripts": { "start": "webpack --config webpack.prod.config.js", "dev": "webpack-dev-server --config webpack.dev.config.js" }
15. Devtool enhanced debugging process in Webpack
We can
devtool
set up the enhanced debugging process byBy setting
devtool
: "source-map"Source Map
- The source map is an information file , which stores the location information of the code before and after compression.
- That is, the location information of the original code can be directly displayed during debugging , instead of the compressed one, which greatly facilitates later debugging
The Source Map generated by default in the development environment records the location of the generated code. This will cause the problem that the number of lines in the runtime error is inconsistent with the number of lines in the source code.
Solution: Add the following configuration in webpack.dev.config.js to ensure that the number of lines that report errors at runtime is consistent with the number of lines in the source code
// webpack.dev.config.js 开发环境 const path = require("path") const {merge} = require("webpack-merge") const webpackConfig = require("./webpack.config") const devConfig = { // 开发模式 mode:"development", //此选项生成的 Source Map 能保证运行时的报错行数与源代码的行数保持一致 devtool:"source-map", devServer:{ // 服务器打开目录 static:path.join(__dirname,"public"), // 压缩 compress:true, // 端口 port:9000, // 实时更新 hot:true, // 自动打开浏览器 open:true, // 使用history路由模式,若404报错时被代替为index.html historyApiFallback:true } } module.exports = merge(webpackConfig,devConfig)
// webpack.prod.config.js 生产环境 const {merge} = require("webpack-merge") const webpackConfig = require("./webpack.config") const prodConfig = { // 生产模式 mode:"production", // 隐藏错误,不进行提示 devtool:"hidden-nosources-source-map" } module.exports = merge(webpackConfig,prodConfig)
Best Practices for Source Maps
In development mode
It is recommended to directly set the value of devtool to
source-map
, which can directly locate the specific error lineIn production environment
It is recommended to turn off Source Map or set devtool
hidden-nosources-source-map
to prevent source code leakage and improve website security.
16. .browserslistrc file description
The browserslistrc file is to indicate the browser compatibility of the current project
There are three ways to use it:
- set in package.json
- Set as a separate configuration file
- Some plugins require resetting browserslist
We refer to the environment configuration of the Vue project, choose the second method, and set it as an independent configuration file.
.browserslistrc
Create a file in the root directory of the project> 1% // 兼容市场上占有率超过1%的浏览器(世界级) last 2 versions // 兼容浏览器最近的两个版本 not dead // 不支持24个月内没有官方支持或者更新的浏览器 not ie 11 // 不支持ie 11
17.postcss-loader handles css compatibility
Postcss is a tool for JavaScript conversion styles. This tool can handle CSS compatibility issues . It is this tool that can add some compatible prefixes to the css code we write.
cnpm install --save-dev [email protected] cnpm install --save-dev [email protected] cnpm isntall --save-dev [email protected] cnpm install --save-dev [email protected]
postcss.config.js
Create a file in the project root directory// postcss.config.js module.exports = { plugins: { "autoprefixer":{ "overrideBrowserslist":[ // 兼容IE7以上浏览器 "ie >= 8", // 兼容火狐版本号大于3.5浏览器 "Firefox >= 3.5", // 兼容谷歌版本号大于35浏览器, "chrome >= 35" ] } } }
Modify files
webpack.config.js
rules: [ { test: /\.css$/, use:[MiniCssExtractPlugin.loader ,"css-loader","postcss-loader"] }, { test: /\.less$/, use:[MiniCssExtractPlugin.loader ,"css-loader","postcss-loader","less-loader"] }, { test: /\.(scss|sass)$/, use:[MiniCssExtractPlugin.loader ,"css-loader","postcss-loader","sass-loader"] } ]
#root{ color: greenyellow; display: flex; }
as follows:
Reported an error
Run in a terminal in the root directory where the project is running: cnpm install
Then restart the development environment in the root directory where the project is running: npm run dev and it will run.
18.Webpack builds React environment
At present, the two most commonly used front-end frameworks of React and Vue use Webpack to build projects
Next, we use
webpack
the environment to build a React projectInstall
cnpm install -D @babel/[email protected] cnpm install -S [email protected] cnpm install -S [email protected]
Add configuration file
The grammar used by React is
jsx
grammar, so we need to configurejsx
the parsing module// 解析react文件 { test: /\.(js|jsx)$/, exclude: /node_modules/, loader: 'babel-loader' }
At the same time we need to modify the file
babel.config.js
module.exports = { presets: [ '@babel/preset-env', "@babel/preset-react" ] }
Writing React code
import React from 'react' import ReactDom from 'react-dom' class App extends React.Component { render(){ return ( <div style={ {color:"#333"}}> Hello </div> ) } } ReactDom.render(<App/>,document.getElementById("root"))
Finally run the development environment ( npm run dev ): the react project environment is configured
19. Webpack builds Vue environment
At present, the two most commonly used front-end frameworks of React and Vue use Webpack to build projects
Next, we use
webpack
the environment to build a Vue projectInstall
When it comes to Vue-specific files
.vue
, we need some package help to parse them.cnpm install --save [email protected] cnpm install --save-dev [email protected] cnpm install --save-dev [email protected] cnpm install --save-dev [email protected] cnpm install --save-dev [email protected]
Add configuration file
in file
webpack.config.js
const { VueLoaderPlugin } = require('vue-loader') const baseConf = { module:{ { test: /\.vue$/, use: ['vue-loader'] } }, plugins:[ new VueLoaderPlugin() ] }
Writing Vue code
// index.js import { createApp } from 'vue' import App from './App.vue' createApp(App).mount('#root')
// App.vue <template> <p>Vue文件环境测试</p> </template> <script> export default { } </script> <style> p{ color: red; } </style>
20.Webpack image processing
In Webpack, everything is a module, and images are no exception. We also need to deal with them separately.
Install
Image processing is done through
url-loader file-loader
cnpm install --save-dev [email protected] cnpm install --save-dev [email protected]
Add configuration ( webpack.config.js )
{ test: /\.(png|svg|jpe?g|gif)$/i, use: { loader:"url-loader", options:{ // 阈值,小于20 * 1024kb,进行base64转码 limit:20 * 1024, // img/存放路径 [name]:图片名字 [hash:8]:hash8位 [ext]:后缀 name:"img/[name].[hash:8].[ext]" } } }
Then add pictures to the files in the src directory
At this point, you can add a picture with an effect of 20 * 1024 kb and test it.
Kind tips
If the image is larger than 20 * 1024kb, you need to install
file-loader
npm install --save-dev [email protected]
You no longer need to do any additional operations to import files larger than 20 * 1024kb, and copy them directly to
dist/img/
the directory.Special Note
The font icons here are also identifiable. This is also the advantage brought by the Webpack5 version. It is processed all at once.
21.Proxy in Webpack (actually a cross-domain issue)
When making network requests, the most common problem on the front end is cross-domain, which can be handled on the front end and back end respectively.
front end
- JSONP (requires server-side support)
- proxy proxy (development mode)
rear end
- cors
Install network request scheme
cnpm install --save-dev [email protected]
Add configuration
adding configuration
webpack.dev.config.js
devServer:{ proxy: { //定义一个标记,如以后api开头的请求都走代理的设置 '/api': { // 要请求的真实服务端基地址 相当于被/api替代了 target: 'http://iwenwiki.com', //把api重写为空,因为别人没有 /api pathRewrite: { "^/api": "" }, //发送请求头中host会设置成target changeOrigin: true } } }
// App.vue <template> <p>Vue文件环境测试</p> <img src="./assets/1.jpg" alt=""> </template> <script> import axios from "axios" export default { mounted(){ axios.get("/api/api/FingerUnion/list.php").then(res =>{ console.log(res.data); }) } } </script> <style> p{ color: red; } </style>
In this way, information can be obtained and cross-domain problems can be solved.
22. Automatically clean dist
In order to automatically clean up the files in the dist directory each time it is packaged and released (to prevent old files from being retained)
Plug-ins can be installed
clean-webpack-plugin
Install
cnpm install --save-dev [email protected]
Plug-in configuration
// webpack.prod.config.js const commonConfig = require("./webpack.config"); const { merge } = require("webpack-merge"); const { CleanWebpackPlugin } = require('clean-webpack-plugin') const cleanPlugin = new CleanWebpackPlugin() const prodConfig = { mode: 'production', devtool: 'nosources-source-map', plugins: [cleanPlugin] } module.exports = merge(commonConfig, prodConfig)
23. Webpack optimization
There have been many previous operations on Webpack for Webpack optimization, such as: separating development and production environments, separating and compressing CSS code, adding and optimizing
devtool
debugging of development and production environments, etc.Next, we will introduce some optimization solutions:
- Specify document processing area
- Check the file size, if it is too large, deal with it
Specify document processing area
There are a lot of js files in the project, especially in
node_modules
folders, but what we need to deal with are thosesrc
in the directorySo we need to specify the area
{ test: /\.js$/, use: ['babel-loader'], // 包含只处理 src 目录下的文件 include: path.resolve(__dirname, 'src'), }
Check the file size, if it is too large, deal with it
webpack-bundle-analyzer
It is a packaging analysis artifact. Its interface is also clear, and it can intuitively give the size of each packaged file and its respective dependencies, which can help us analyze the project more conveniently.Install:
cnpm install --save-dev webpack-bundle-analyzer
Add configuration:
// webpack.dev.config.js 开发环境 const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer'); module.exports = { plugins: [ new BundleAnalyzerPlugin({ analyzerPort: 8888, // 指定端口号 openAnalyzer: false, }) ] }
24. Code inspection in JavaScript
A very important thing for a front-end team is code specifications. Only with code specifications can the code quality be ensured.
Common front-end code specification tools:
- JSLint
- JSHint
- ESLint
Of course, we recommend it here first
ESLint
, and we will also integrate it in subsequent Webpack.ESLint
JSLint
Advantages: The configuration has been determined by experienced experts and can be used right out of the box.
shortcoming:
- Limited configuration options, many rules cannot be disabled
- The regulations are strict, and anyone who does not conform to what the veteran considers to be a good style will be given a warning.
- poor scalability
- Unable to locate the corresponding rule based on the error
JSHint
advantage:
- There are many parameters that can be configured
- Support configuration files for easy use
- Supports some common class libraries
- supports the basic
ES6
shortcoming:
- Does not support custom rules
- Unable to locate the corresponding rule based on the error
ESLint
advantage:
- The default rules include
JSLint
andJSHint
rules, which are easy to migrate- Can be configured to
警告
two错误
levels, or disabled directly- Support plug-in extension
- Rules can be customized
- Corresponding rules can be located based on errors
- support
ES6
- The only
JSX
tool supportedshortcoming:
- Some custom configuration is required (because it is too flexible, but the documentation is very detailed)
- Slow (it's slower than the other two)
25.Configuring ESLint in Webpack
In order to unify and standardize team coding habits and reduce the risk of code errors, eslint has become an essential tool for front-end projects.
To put it simply, writing code must follow certain norms, as for what norms, we can define by ourselves
ESLint official website
Install dependencies
cnpm install [email protected] [email protected] --save-dev
webpack configuration file ( webpack.dev.config.js )
// webpack.dev.config.js 文件中 const ESLintPlugin = require('eslint-webpack-plugin'); module.exports = { plugins: [new ESLintPlugin()], };
.eslintrc.js
Add a new file in the root directorymodule.exports = { env: { node: true, browser: true, es6: true, }, // 支持ES6并不代表支持所有ES6新语法, 设置为 "module" 支持 ECMAScript 模块 parserOptions: { sourceType: 'module' }, rules: { // JS文件中不支持console.log() 'no-console': 2 }, };
Common ESLint Specifications
"no-alert": 0,//Disable the use of alert confirm prompt
"no-array-constructor": 2,//Disable the use of array constructor
"no-bitwise": 0,//Disable the use of bitwise operators
"no-caller": 1,//It is forbidden to use arguments.caller or arguments.callee
"no-catch-shadow": 2,//Prohibit catch clause parameters with the same name as external scope variables
"no-class-assign": 2, //Assignment to classes is prohibited
"no-cond-assign": 2,//Prohibit the use of assignment statements in conditional expressions
"no-console": 2,//Disable the use of console
"no-const-assign": 2,//Prohibit modification of variables declared by const
"no-constant-condition": 2,//Prohibit the use of constant expressions in conditions if(true) if(1)
"no-continue": 0, //Disable the use of continue
"no-control-regex": 2,//Disallow the use of control characters in regular expressions
"no-debugger": 2,//Disable the use of debugger
"no-delete-var": 2,//The delete operator cannot be used on variables declared by var
"no-div-regex": 1, // cannot use regular expressions that look like division /=foo/
"no-dupe-keys": 2,//Do not allow duplicate keys {a:1,a:1} when creating object literals
"no-dupe-args": 2,//function parameters cannot be repeated
"no-duplicate-case": 2, //case labels in switch cannot be repeated
"no-else-return": 2,//If there is return in the if statement, it cannot be followed by an else statement.
"no-empty": 2, //The content in the block statement cannot be empty
"no-empty-character-class": 2, // [] content in the regular expression cannot be empty
"no-empty-label": 2, //Disable the use of empty labels
"no-eq-null": 2, //Disallow the use of == or != operators for null
"no-eval": 1,//Disable the use of eval
"no-ex-assign": 2,//Prohibit assigning values to the exception parameters in the catch statement
"no-extend-native": 2, //Disable extension of native objects
"no-extra-bind": 2,//Prohibit unnecessary function binding
"no-extra-boolean-cast": 2, //Disable unnecessary boolean conversion
"no-extra-parens": 2,//Prohibit unnecessary parentheses
"no-extra-semi": 2, // prohibit extra colons
"no-fallthrough": 1, //Disable switch penetration
"no-floating-decimal": 2,//It is forbidden to omit 0.5 in floating point numbers 3.
"no-func-assign": 2, //Disable duplicate function declarations
"no-implicit-coercion": 1,//Disable implicit conversion
"no-implied-eval": 2, // disable implicit eval
"no-inline-comments": 0, //Inline comments are prohibited
"no-inner-declarations": [2, "functions"], // prohibit the use of declarations (variables or functions) in block statements
"no-invalid-regexp": 2,//Disable invalid regular expressions
"no-invalid-this": 2, //Invalid this is prohibited and can only be used in constructors, classes, and object literals
"no-irregular-whitespace": 2,//There cannot be irregular spaces
"no-iterator": 2,//It is forbidden to use the iterator attribute
"no-label-var": 2, //label name cannot be the same as the variable name declared by var
"no-labels": 2, // prohibit label declaration
"no-lone-blocks": 2,//Disable unnecessary nested blocks
"no-lonely-if": 2,//Prohibit only if statements within else statements
"no-loop-func": 1,//Prohibit the use of functions in loops (if no external variables are referenced and no closure is formed)
"no-mixed-requires": [0, false], //Declaration types cannot be mixed
"no-mixed-spaces-and-tabs": [2, false], //Disallow mixing tabs and spaces
"linebreak-style": [0, "windows"], //linebreak style
"no-multi-spaces": 1,//Cannot use extra spaces
"no-multi-str": 2,//The string cannot be wrapped with \
"no-multiple-empty-lines": [1, {"max": 2}],//Empty lines cannot exceed 2 lines at most
"no-native-reassign": 2,//Cannot rewrite native object
"no-negated-in-lhs": 2, //the left side of the in operator cannot have !
"no-nested-ternary": 0,//Disable the use of nested ternary operations
"no-new": 1,//It is forbidden to use new to construct an instance without assigning a value.
"no-new-func": 1, //Disable the use of new Function
“no-new-object”: 2,//Forbidden use new Object()
"no-new-require": 2, //Disable the use of new require
"no-new-wrappers": 2,//It is forbidden to use new to create wrapper instances, new String new Boolean new Number
"no-obj-calls": 2,//Cannot call built-in global objects, such as Math() JSON()
"no-octal": 2,//It is forbidden to use octal numbers
"no-octal-escape": 2, //Disallow the use of octal escape sequences
"no-param-reassign": 2,//Prohibit reassigning parameters
"no-path-concat": 0, // dirname or filename cannot be used for path concatenation in node
"no-plusplus": 0,//It is forbidden to use ++, –
"no-process-env": 0, //Prohibit the use of process.env
“no-process-exit”: 0,//Prohibited use process.exit()
"no-proto": 2,//It is forbidden to use the proto attribute
"no-redeclare": 2, //Do not redeclare variables
"no-regex-spaces": 2,//Prohibit the use of multiple spaces in regular expression literals /foo bar/
"no-restricted-modules": 0, //If the specified module is disabled, an error will be reported when using it.
"no-return-assign": 1,//There cannot be an assignment expression in the return statement
"no-script-url": 0,//Disable the use of javascript:void(0)
"no-self-compare": 2,//cannot compare itself
"no-sequences": 0, // prohibit the use of the comma operator
"no-shadow": 2, //A variable in the outer scope cannot have the same name as a variable or parameter in the scope it contains
"no-shadow-restricted-names": 2, //Restricted identifiers specified in strict mode cannot be used as variable names when declaring
"no-spaced-func": 2,//There can be no space between the function name and () when the function is called
"no-sparse-arrays": 2, //Forbid sparse arrays, [1,2]
"no-sync": 0,//nodejs prohibits synchronization methods
"no-ternary": 0, //Disable the use of ternary operators
"no-trailing-spaces": 1,//Do not have spaces after the end of a line
"no-this-before-super": 0, // cannot use this or super before calling super()
"no-throw-literal": 2,//Prohibit throwing literal errors throw
"error"; "no-undef": 1,//There cannot be undefined variables
"no-undef-init": 2,//When initializing a variable, you cannot directly assign it a value of undefined
"no-undefined": 2, //undefined cannot be used
"no-unexpected-multiline": 2, //Avoid multi-line expressions
"no-underscore-dangle": 1, //The identifier cannot start or end with _
"no-unneeded-ternary": 2,//Prohibit unnecessary nesting var isYes = answer === 1 ? true : false;
"no-unreachable": 2, //There cannot be unexecutable code
"no-unused-expressions": 2,//Disable useless expressions
"no-unused-vars": [2, {"vars": "all", "args": "after-used"}], //There cannot be variables or parameters that have not been used after declaration
"no-use-before-define": 2,//Cannot be used before it is defined
"no-useless-call": 2,//Prohibit unnecessary calls and apply
"no-void": 2, // disable void operator
"no-var": 0, //Disable var, use let and const instead
“no-warning-comments”: [1, { “terms”: [“todo”, “fixme”, “xxx”], “location”: “start” }],//There cannot be warning comments
"no-with": 2, // disable with
"array-bracket-spacing": [2, "never"], //Whether extra spaces are allowed in non-empty arrays
"arrow-parens": 0,//Arrow functions are enclosed in parentheses
"arrow-spacing": 0,//=> before/after brackets
"accessor-pairs": 0,//Use getter/setter in the object
"block-scoped-var": 0, //Use var in block statements
"brace-style": [1, "1tbs"],//Braces style
"callback-return": 1,//Avoid calling callbacks multiple times or something like that
"camelcase": 2, // Force camel case naming
"comma-dangle": [2, "never"], //Object literals cannot have commas at the end
"comma-spacing": 0, //spaces before and after comma
"comma-style": [2, "last"],//Comma style, whether the line breaks at the beginning or end of the line
"complexity": [0, 11],//Cyclic complexity
"computed-property-spacing": [0, "never"], //Whether calculated key names are allowed or not
"consistent-return": 0, //Whether omission is allowed after return
“consistent-this”: [2, “that”],//this别名
"constructor-super": 0,//Non-derived classes cannot call super, derived classes must call super
"curly": [2, "all"],//Must use {} in if(){}
"default-case": 2, //switch statement must have default at the end
"dot-location": 0,//The location of the object accessor, whether it is at the beginning or the end of the line when wrapping
"dot-notation": [0, { "allowKeywords": true }], // avoid unnecessary square brackets
"eol-last": 0, //The file ends with a single newline
"eqeqeq": 2, //Must use congruence "func-names": 0,//Function expression must have a name
"func-style": [0, "declaration"],//function style, which stipulates that only function declarations/function expressions can be used
"generator-star-spacing": 0, // spaces before and after the generator function *
"guard-for-in": 0, //for in loop should be filtered by if statement
"handle-callback-err": 0, //nodejs handles errors
"id-length": 0, // variable name length
"indent": [2, 4],//indent style
"init-declarations": 0,//The initial value must be assigned when declaring
"key-spacing": [0, { "beforeColon": false, "afterColon": true }],//The spaces before and after the colon in the object literal
"lines-around-comment": 0,//Remarks before/after the line
"max-depth": [0, 4],//Nested block depth
"max-len": [0, 80, 4],//Maximum length of string
"max-nested-callbacks": [0, 2],//Callback nesting depth
"max-params": [0, 3], //The function can only have up to 3 parameters
"max-statements": [0, 10],//There are at most several statements in the function
"new-cap": 2,//The first line of the function name in capital letters must be called using the new method, and the first line of the function name in lower case letters must be called without the new method.
"new-parens": 2, // parentheses must be added when new
"newline-after-var": 2,//Whether a blank line is required after variable declaration
"object-curly-spacing": [0, "never"], //Whether unnecessary spaces are allowed within curly brackets
"object-shorthand": 0,//Force object literal abbreviation syntax
"one-var": 1,//Continuous declaration
"operator-assignment": [0, "always"],//Assignment operator += -= or something
"operator-linebreak": [2, "after"],//When breaking a line, whether the operator is at the end of the line or at the beginning of the line
"padded-blocks": 0,//Whether there should be a blank line at the beginning and end of the line in the block statement
"prefer-const": 0, // prefer const
"prefer-spread": 0,//preferred expansion operation
"prefer-reflect": 0,//Preferred Reflect method
"quotes": [1, "single"],//Quotation mark type `` "" ''
"quote-props":[2, "always"],//Whether the attribute name in the object literal must be double quoted
"radix": 2, //parseInt must specify the second parameter "id-match": 0, // naming detection
"require-yield": 0, //The generator function must have yield "semi": [2, "always"], //The statement is forced to end with a semicolon
“semi-spacing”: [0, {“before”: false, “after”: true}], //spaces before and after the semicolon
"sort-vars": 0, //Sort when variables are declared
"space-after-keywords": [0, "always"],//Whether there should be a space after the keyword
"space-before-blocks": [0, "always"], //Blocks that do not start with a new line {should there be a space in front of them
"space-before-function-paren": [0, "always"],//When defining a function, should there be a space before the parentheses?
“space-in-parens”: [0, “never”],//Should there be spaces in the parentheses?
"space-infix-ops": 0,//Should there be spaces around the infix operator?
"space-return-throw-case": 2,//Do you need to add a space after the return throw case?
"space-unary-ops": [0, { "words": true, "nonwords": false }], // Do you want to add spaces before/after unary operators
"spaced-comment": 0, //Do you want the comment style to have spaces or anything like that?
"strict": 2,//Use strict mode
"use-isnan": 2,//Disable the use of NaN when comparing, only isNaN() can be used
"valid-jsdoc": 0,//jsdoc rules
"valid-typeof": 2,//Must use a valid typeof value
"vars-on-top": 2, //var must be placed at the top of the scope
"wrap-iife": [2, "inside"], //The parenthesis style of immediately executing function expressions
"wrap-regex": 0, //The regular expression literal is wrapped in parentheses
"yoda": [2, "never"]//Prohibit expression conditions
It is difficult for individuals to formulate large and comprehensive specifications. At this time, we can borrow mature solutions from large companies and then slightly modify them according to the project situation. Here we quote Airbnb
Install
Airbnb
rule dependenciescnpm install [email protected] [email protected] --save-dev
Used in eslint configuration file
Airbnb
module.exports = { env: { node: true, browser: true, es6: true, }, // 支持ES6并不代表支持所有ES6新语法, 设置为 "module" 支持 ECMAScript 模块 parserOptions: { sourceType: 'module' }, extends: "airbnb-base", rules: { // JS文件中不支持console.log() 'no-console': 2 }, };
If you write non-standard code at this time, you will find that many new rules have been added, which requires us to correct them one by one.