Yarn package manager

Similar to NPM, YARN is a package management tool that can be used to download packages. However, YARN is faster than NPM

Download address: yarn.bootcss.com/docs/instal…

Basic commands:

// 1. Initialize yarn init/yarn init -y // 2. Add dependency yarn add [package] yarn add [package]@[version] // 3. Yarn remove [package] // 4. Installation projects depend on YARN or yarn install // 5. Global YARN Global add [package] // Install YARN Global remove [package] // Uninstall yarn GlobalCopy the code

Webpack overview

Webpack is a NodeJs-based static module bundler (vue-CLI scaffolding environment, integrated with WebPack)

Webpack Chinese document: webpack.docschina.org/concepts/

What can Webpack do

Webpack is a static module packer

  1. The syntax conversion
    • Less/SASS is converted to CSS
    • ES6 is converted to ES5
    • Typescript converts to native JS
    • .
  2. HTML/CSS/JS code compression merge (packaging)
  3. Webpack can improve development efficiency by providing a development server during development

Usually the project will be packaged before it goes online

Webpack – Basic use

Webpack packages the demo

  1. Dist public/index.html SRC /main.js

    Dist public SRC md dist md public md SRC dist public SRC Create folder js CSS img less fonts CD SRC MD js // MD CSS md img md less md fonts // create index.js file CD js new-item in SRC /js folder Index. js // Create index. HTML CD.. /.. /public new-item index.html cd ..Copy the code
    <span class="iconfont icon-pic-fill"></span> <ul> <li> I am the first li</li> <li> </li> <li> I am the third li</li> <li> I am the fourth li</li> <li> I am the fifth li</li> <li> I am the sixth li</li> <li> I am the seventh li</li> <li> I am the eighth li</li> <li> I am the ninth li</li> <li> I am the 10th li</li> </ul> // index.js import '.. /css/index.css' import '.. /less/aaa.less' const $ = require('jquery'); import imgObj from '.. /img/02.gif' import '.. /fonts/iconfont.css' $(function () { $('ul li:odd').css('color','red') $('ul li:even').css('color','green') const $img = $(' < img > ') $img. Attr (' SRC 'imgObj) $(" body "). The prepend ($img)}) const fn () = = > {the console. The log (' this is a fn); }Copy the code
  2. Initialize the

    Json yarn init -y in the outermost layerCopy the code
  3. Installing dependency packages

    // Install the dependency package and generate the node_modules folder and yarn.lock file in the outermost layer yarn add webpack webpack-cli -dCopy the code

    Dependencies: jquery yarn Add jquery

    DevDependencies -d -d -d -d -d -d -d -d -d -d -d -d -d -d -d -d -d -d -d -d -d -d -d

  4. The configuration scripts

    // Add configuration "scripts": {"build": "webpack --config webpack.config.js"}Copy the code

    –config webpack.config.js –config webpack.config.js –config webpack.config.js –config webpack.config.js

  1. Provide webpack. Config. Js

    // Create a new webpack.config.js file on the outermost layer. New-item webpack.config.jsCopy the code
  2. Add entry and exit

    // Add entry and exit to webpack.config.js const path = require('path') module.exports = {// add entry to webpack.config.js const path = require('path') module.exports = { './ SRC /js/index.js', // output: configuration output (where to package) output: {// Directory to package output (must be absolute path) path: Path. join(__dirname, 'dist'), // Package the generated filename filename: 'index.js',}, // Package mode production compression /development uncompression mode: 'development', }Copy the code
  3. Execute the script

    yarn build
    Copy the code

The usage of scripts in package.json

In the package.json file, you can configure scripts… Configure your own commands

"scripts": {
	"pp": "yarn add jquery",
	"build": "webpack --config webpack.config.js"
}
Copy the code
yarn xxx
npm run pp
npm run build
Copy the code

Run mode: NPM run xx

Special commands: start/stop can omit run

npm run start  => npm start      =>  yarn start
npm run stop  => npm stop        =>  yarn stop
Copy the code

Run is not required to use YARN

npm run pp  =>  yarn pp
npm run build => yarn build
Copy the code

< li > interlaced color change based on Webpack

  1. Create some new Li’s in 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>Document</title> </head> <body> <p> This is p</p> <ul> <li> <li> I am the third li</li> <li> I am the fourth li</li> <li> I am the fifth li</li> <li> I am the sixth li</li> <li> I am the seventh li</li> <li> I am the eighth li</li> <li> I am the ninth li</li> <li> I am the 10th li</li> </ul> </body> </ HTML >Copy the code
  2. Install jquery and write code

    yarn add jquery
    Copy the code
  3. In SRC /js/index.js, interlacing color is implemented with jquery

    import $ from 'jquery'
    $(function () {
        $('ul li:odd').css('color', 'red')
        $('ul li:even').css('color', 'green')
    })
    Copy the code
  4. Execute pack command

    yarn build
    Copy the code
  5. Manually copy public/index.html to the dist directory and import the packaged JS manually

    <script src="./index.js"></script>
    Copy the code

  1. Run index.html under dist

Webpack – Configuration of plug-ins and loaders

Automatic HTML generationhtml-webpack-pluginThe plug-in

Every time you have to manually copy public/index.html to the dist directory, manually importing the packaged JS is too cumbersome

So there’s usually a plug-in that’s automatically copied into dist and automatically imported

  1. download

    yarn add html-webpack-plugin  -D
    Copy the code
  2. In the webpack.config.js file, introduce this module:

    // const HtmlWebpackPlugin = require('html-webpack-plugin')Copy the code
  3. configuration

    plugins: [
      new HtmlWebpackPlugin({ template: './public/index.html' })
    ]
    Copy the code

    Once configured, the index. HTML of the public directory does not need to import the packaged file and is automatically imported by the plug-in generated HTML

  1. Execute pack command

    yarn build
    Copy the code
  2. Dist automatically generates index.html, and the index.html file automatically introduces index.js

  1. Run index.html under dist

Handling CSS files in Webpack –css-loader

Webpack only knows JS and JSON files by default, but WebPack can use a loader to load preprocessed files, allowing WebPack to package static resources outside of JS as well.

So if WebPack wants to handle other file types, remember to configure the corresponding loader first

Requirement: Remove the dots and create a CSS directory

  1. Create an index. CSS file in the SRC/CSS folder and add styles to remove the dots

    cd src/css new-item index.css cd .. /..Copy the code
    * {
        margin: 0;
        padding: 0;
    }
    li {
        list-style: none;
    }
    Copy the code
  2. Install dependencies

    yarn add style-loader css-loader -D
    Copy the code
  3. SRC, add index.css to index.js

    Import $from 'jquery' import $from 'jquery' import 'index.css' import '.. /css/index.css' $(function () { $('ul li:odd').css('color', 'red') $('ul li:even').css('color', 'green') })Copy the code
  4. configuration

    Module. exports adds module: {// loader rules: [{// regular expressions used to match all CSS files test: CSS $/, // Use css-loader to enable webpack to identify the contents of the CSS file. // Use style-loader to add styles to the page. [ "style-loader", "css-loader"] } ] },Copy the code
  5. Execute pack command

    yarn build
    Copy the code

Separating CSS filesmini-css-extract-plugin

What we did above has caused the CSS and JS files to get mixed up

CSS is not found to be introduced, but the styling of the index. CSS setting does take effect

Plug-in: mini – CSS – extract – the plugin

  1. Installing dependency packages

    yarn add mini-css-extract-plugin -D
    Copy the code
  2. inwebpack.config.jsFile, import this module

    // const MiniCssExtractPlugin = require('mini-css-extract-plugin')Copy the code

  1. Configuration loaders

    Use: [/ / according to the official document writing, pay attention to the position of 'CSS - loader' writing MiniCssExtractPlugin. Loader, 'CSS - loader]Copy the code

  1. Plug-in configuration

    plugins: [ new HtmlWebpackPlugin({ template: New MiniCssExtractPlugin({filename:' CSS /index.css'})],Copy the code

  1. Execute pack command

    yarn build
    Copy the code
  2. Dist /index.html, js and CSS are introduced and separated successfully

Handle less – in Webpackless-loader

  1. Create the aaA. less file in the SRC /less folder

    cd src/less new-item aaa.less cd .. /..Copy the code

    Set the P tag style in aaA.less

    p{
        color: blue;
    }
    Copy the code
  2. Downloading dependency packages

    Note: Parsing less files requires recognizing the less syntax, so you need to download additional less packages in addition to less-loader

    Less-loader: converts less to CSS

    yarn add less  less-loader  -D
    Copy the code
  3. SRC, add aaa. Less to index.js

  1. configuration

    / / less configuration file parsing {test: / \. Less $/, use: [/ / CSS was isolated contents MiniCssExtractPlugin. Loader, 'CSS - loader', 'less - loader]}Copy the code

  1. Execute pack command

    yarn build
    Copy the code
  2. Aaa. Less is successfully imported, and the P label turns blue

Image processing in Webpack – built-in Asset Module

Place 01.jpg and 02.gif in the SRC /img folder in advance

  1. An error occurs when inserting images directly into HTML

    import imgObj from '.. /img/02.gif' $(function() { const $img = $('<img>') $img.attr('src', imgObj) $('body').append($img) })Copy the code

    In this case, you need to use the built-in Asset resource processing module of WebPack5 to process image resources

    Webpack5 processing resources: webpack.docschina.org/guides/asse…

    Tips: WebPack4 is used to deal with the problem of images, mainly using two modules of url-loader and file-loader. Now WebPack5 has been integrated, no installation is required.

  1. ** Configuration rules Basic rule: **

    {
      test: /\.(png|jpg|gif|jpeg)$/i,
      type: 'asset'
    }
    Copy the code
    • For images less than 8K, the base64 string is automatically transferred (save requests, cost: put about 30% of the image volume size)

    • For images larger than 8K, a separate file import is generated.

  2. Configure the image package output directory:

    The default is to output directly to the dist root and can be configured using generator

    {
      test: /\.(png|jpg|gif|jpeg)$/i,
      type: 'asset',
      generator: {
        filename: 'images/[hash][name][ext]'
      }
    }
    Copy the code

  1. Execute pack command

    yarn build
    Copy the code

    The images folder was successfully generated under the dist folder

  1. Dist /index.html, insert image successfully

Webpack configures font ICONS – consistent with images

The font icon and picture are configured the same

  1. Prepare the font icon file

  1. Introduce font ICONS in public/index.html files

    <span class="iconfont icon-pic-fill"></span>
    Copy the code
  2. Add iconfont. CSS to SRC /js/index.js

  1. Execute pack command

    yarn build
    Copy the code
  2. Open dist/index.html and add font icon successfully

Webpack uses Babel to handle higher versions of JS syntax

Webpack only has the modular compatibility handle Import Export built in by default

Introduction to Babel => for handling compatibility with older JS syntax

  1. The installation package

    yarn add -D babel-loader @babel/core @babel/preset-env
    Copy the code
  2. Configuration rules

    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /(node_modules|bower_components)/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: ['@babel/preset-env']
            }
          }
        }
      ]
    }
    Copy the code
  3. Add an arrow function from ES6 to SRC /js/index.js

    Const fn=()=>{console.log(' This is a FN '); }Copy the code
  4. Execute pack command

    yarn build
    Copy the code
  5. Dist /index.js is opened, and the arrow function is converted to a normal function function

Webpack – Development server

Webpack-dev-server automatically refreshes

  1. download
yarn add webpack-dev-server -D
Copy the code
  1. The configuration scripts
"scripts": {
	"build": "webpack --config webpack.config.js",
	"dev": "webpack serve --config webpack.config.js"
}
Copy the code

  1. Execute pack command

    yarn dev
    Copy the code
  2. After port 8080 is enabled manually by default, it can be refreshed automatically

Webpack dev – server configuration

  1. Change the port number that webpack-dev-server opens by default and set the browser to open automatically
DevServer: {port: 3000, // port number open: true // automatically open browser}Copy the code

  1. Execute pack command
yarn dev
Copy the code