current position:Home>Vue - 10 - webpack packaging nanny level tutorial 01 - packaging JS, JSON, CSS, less, HTML, background pictures and pictures, font files, devserver, production environment configuration and compatible writing of CSS

Vue - 10 - webpack packaging nanny level tutorial 01 - packaging JS, JSON, CSS, less, HTML, background pictures and pictures, font files, devserver, production environment configuration and compatible writing of CSS

2022-01-27 01:26:47 Nanchen_ forty-two

Catalog

One 、webpack pack JS file  

1. New entry file index.js and mathUtils.js,index.js It depends on mathUtils.js

2、 And then use webpack Command packaging js file  

Two 、 pack JSON file

The first packaging method

The second packaging method :webpack pack

The third packaging method : establish webpack.config.js

The fourth packaging method : Use custom scripts (script) start-up                 ****( important )

3、 ... and 、 pack css Files use webpack Of loader

What is? loader

loader Use

Four 、 Yes less Package files

1、 newly build less file

​ 2、 introduce less

 3、 install less-loader

 4、 stay webpack.config.js Use in less-loader

 5、 perform npm run build

5、 ... and 、 Package background pictures

attach : Convert the picture to base64 Advantages and disadvantages of format  

6、 ... and 、 pack Font Font style and HTML

7、 ... and 、devsever

8、 ... and 、webpack Production environment configuration

* Nine 、css Compatibility writing

Ten 、html Inside img How to package the pictures in the label


One 、webpack pack JS file  

Be careful : Be sure to download Node.js,webpack Must be in NodeJS Run under

If not downloaded, it can be downloaded from Vue—— install @vue/cli(Vue The scaffold ) In three ways   View and download

First, select a disk and create a folder for webpack( Names can be defined by themselves ), Add two new folders to the folder scr as well as dist

Hold down win+r Input cmd Call up the console , Enter the correct path

 

  Then initialize :npm init

Then keep going back  , Until the directory appears again

You'll find more json file

 

  After input :

Global installation :

npm i webpack webpack-cli -g

Local installation :

npm i webpack webpack-cli -D

After installation, you will find multiple folders in the directory

  stay src Create two new... In the folder js file

1. New entry file index.js and mathUtils.js,index.js yes Depend on mathUtils.js

mathUtils.js The code part is as follows :

//1. newly build mathUtils.js, use CommonJs Specification export 
function add(num1,num2) {
  return num1+num2
}
function mul(num1,num2) {
  return num1*num2
}
module.exports = {
  add,mul
}

index.js The code part is as follows :

//2. A new entry js file index.js  Import mathUtil.js file , And call 
const {add,mul} = require("./mathUtils.js")

console.log(add(10,20))
console.log(mul(10,10))

When finished, look at the figure below :

2、 And then use webpack Command packaging js file  

Be careful :webpack3 Use the following command !!!

webpack ./src/index.js ./dist/bundle.js

webpack4 And above , Use cmd Enter the following command !!!

webpack ./src/index.js -o ./dist/bundle.js

  Red here , It can be written in a different way

Find the directory , And delete bundle.js Folder

  Then enter the following command :


If it is a development version, use the development environment :

webpack ./src/index.js -o ./dist --mode=development 

If you use the production environment, use this string of code :

webpack ./src/index.js -o ./dist --mode=production

!!    We use the production environment here  

Just report green . In this way, you will find that there is only one place just deleted main.js file

Then you can create a new page to test :

stay dist Create a index.html page , hold main.js Can be introduced

  Running the page :

You can see that you have succeeded  

Two 、 pack JSON file

The first packaging method

for example : stay src Create a new folder data.json file , And enter some json The grammar of

  And then in src In folder index.js Write in

import data from "./data.json"

And print data :

console.log(data);

  Just repack it :

webpack ./src/index.js -o ./dist --mode=production

  This is done webpack The packaging .

  The second packaging method :webpack pack

Directly abbreviated as this, it can also be packaged

webpack You can help us pack js file , Just specify the entry file (index.js) And output files (bundle.js), Whether it's es6 The modularity of is still CommonJs The modular ,webpack Can help us pack , It can also help us deal with the dependencies between modules .

If you feel --mode=development Trouble can be configured webpack.config.js Write as follows

The third packaging method : establish webpack.config.js

Create a new one on the outermost layer webpack.config.js file

write in :

The code is as follows : 

const path = require('path');
module.exports = {
	entry: './src/index.js', // Entrance file 
	output: {
		path: path.resolve(__dirname, 'dist'), // Dynamically obtain the packaged file path ,path.resolve Splicing path 
		filename: 'main.js', // The packaged file name 
	},
    mode:'development'
}

cmd Input : 

webpack

  The printing effect is as follows :

The fourth packaging method : Use custom scripts (script) start-up                 ****( important )

There are two production environments

1、npm run dev// development environment

2、npm run build// Production environment

The production environment is used here, that is     npm run build 

stay package.json Medium scripts Medium plus

"build": "webpack"

Use npm run build package

npm run build

  Input again :


Here's how to pack css file

3、 ... and 、 pack css Files use webpack Of loader

What is? loader

loader yes webpack It's a very central concept in .

webpack Can be js、 picture 、css Handle packing , But for webpack It cannot be handled by itself css、 picture 、ES6 turn ES5 etc. .

At this point, we need webpack An extension of , Use the corresponding loader Can .

loader Use

Step one : adopt npm Install what you need to use loader

Step two : adopt webpack.config.js Medium modules Configure under keyword

Most of the loader Can be in webpack Find the corresponding configuration on our official website .

Create a css file : 

Introducing links : 

stay cmd Enter command in : 

npm run build 

Install and use style-loader as well as css-loader

npm install --save-dev style-loader css-loader

And add... In the configuration loader

The code is as follows : 

  module: {
    rules: [
      {
        test: /\.css$/,// Regular Expression Matching css file 
        //css-loader Only responsible for css File loading , Not responsible for parsing , To parse, you need to use style-loader
        use: [{
          loader: 'style-loader'
        }, {
          loader: 'css-loader'
        }]// Use loader
      }
    ]
  }

Then reload the command : 

webpack The use of multiple loader It's from right to left , So we need to css-loader Put it in style-loader On the right , Load first and then parse .

At this point, the style is loaded and resolved to DOM Element .

Full effect :

Four 、 Yes less Package files

vscode Not directly less To analyze , If you need to parse css Then download the plug-in easy less

1、 newly build less file

 2、 introduce less

 3、 install less-loader

npm install --save-dev less-loader less

 4、 stay webpack.config.js Use in less-loader

module: {
    rules: [
      {
        test: /\.less$/,// Regular Expression Matching css file 
        //css-loader Only responsible for css File loading , Not responsible for parsing , To parse, you need to use style-loader
        use: [{
          loader: 'style-loader'
        }, {
          loader: 'css-loader'
        }, {
          loader: 'less-loader'//less file loader
        }]// Use loader
      }
    ]
  }

If css and less If you need to package, you can write the following code :

module: {
    rules: [{
      test: [/\.css$/i, /\.less$/], // Regular Expression Matching css file 
      //css-loader Only responsible for css File loading , Not responsible for parsing , To parse, you need to use style-loader
      use: [{
        loader: 'style-loader'
      }, {
        loader: 'css-loader'
      }, {
        loader: 'less-loader' //less file loader
      }] // Use loader// Use loader
    }]
  }

Or you could write it as :

module: {
        rules: [
          {
            test:[ /\.css$/i,/\.less$/],
            use: ['style-loader', 'css-loader','less-loader'],
          },
        ],
      },

Here's the picture :

 5、 perform npm run build

According to the effect

5、 ... and 、 Package background pictures

preparation , Prepare two pictures , The size of the picture is one 8KB following ( The name is small.jpg), One larger than 8KB( The name is big.jpg), Create a new one img Folder put two pictures into .

1、 Here it is src New folder img, And put the picture on img In the folder . And created a css Folder , Put the previous css File into it

2、 Bring the background picture into normal.css In the document : 

3、 The corresponding modification is

 4、 stay webpack.config.js Add the following code in :

{
				test: /\.(png|svg|jpg|jpeg|gif)$/i,
				type: 'asset/resource',
				generator: {
					filename: 'images/[hash][ext][query]'
				}// Put the packaged pictures in images Folder 
			},

perhaps

module.exports = {
	mode: 'development',
	entry: './src/index.js', // Entrance file 
	output: {
		path: path.resolve(__dirname, 'dist'), // Dynamically obtain the packaged file path ,path.resolve Splicing path 
		filename: 'bundle.js', // The packaged file name 
		 assetModuleFilename: 'images/[hash:8][ext][query]' // Put the packaged pictures in images Folder 
                                    // hash:8 Is to compile the image into an eight digit hash value 
	},
}

The first method is used here :

  Type the command again

npm run build

  By this time, the packaging has been completed , Go back to the editor and see , You'll find more packed img There are pictures

  Open again index.html,

The display effect is as follows :

Packing is done ! 

There is also an old method

Install and use url-loader Processing images

url-loader image file loader Same job , But if the file is less than the limit , Can return  data URL .( Usually used to process small pictures )

npm install --save-dev url-loader

Install and use file-loader Dealing with big pictures

npm install --save-dev file-loader

Then on webpack.confid.js To configure

 {
        test: /\.(png|jpg|gif)$/i,
         // matching png/jpg/gif Format picture 
        use: [{
          loader: 'url-loader',
          options: {
            limit: 8192, // The picture is smaller than 8KB Turn the picture into base64 character string , Greater than 8KB Need to use file-loader
            esModule: false, // solve es6 Syntax not recognized  
            name: 'img/[name].[hash].[ext]',
          }
        }],
        type: 'javascript/auto'
      }

index.html Be sure to talk to the one below webpack.config.js The export path is consistent !!!!

At this time, we need to src Create a new one in index.html page  

 

  And then run :

npm run build

You can succeed

If the picture is set to 8KB The above picture is in dist Add JS Folders and img Folder

According to the effect : 

If 8KB And the following pictures will only appear JS file , Because of the img The picture is compressed in JS Under folder main.js in

You can see dist Not in China img When you open the folder in the browser, you will find that the format of the picture has been changed  

Convert the picture to base64 Advantages and disadvantages of format  

1. advantage

(1)base64 The format of the picture is text format , It takes up little memory , The size ratio after conversion is about 1/3, Reduce the consumption of resource server ;

(2) Use... In web pages base64 Format of the picture , There is no need to ask the server to call the picture resource , Reduced server access .

(3)base64 Encoded string , More suitable for different platforms 、 Transmission of different languages ;

(4) The algorithm is coding ,  Not compression ,  After encoding, only the number of bytes will be increased , But the algorithm is simple ,  Little impact on efficiency , Algorithm reversible ,  Decoding is very convenient ,  Not used for private information communication ;

(5) Easy decoding ,  But after all, it's coded ,  The naked eye still can't see the original content directly ;

2. shortcoming

(1)base64 There are many text contents in the format , Storing in the database increases the pressure on the database server ;

(2) Although you don't need to visit the server to load pictures on the web page , But because base64 Too much content in the format , So the speed of loading web pages will be reduced , May affect the user experience .

(3)base64 Can't cache , To cache, you can only cache that contains base64 The file of , such as js perhaps css, This is much worse than caching pictures directly , And it's average HTML Frequent changes , So it's equivalent to not getting cache benefits .


Now let's talk about packaging fonts and HTML


6、 ... and 、 pack Font Font style and HTML

First download from Alibaba font gallery to local

Alibaba vector icon library

Select the downloaded icon to Download to local  

After downloading, there is a folder

After opening, put the framed file into src Medium css Folder and new fonts Folder  

 

  change iconfont.css In the path :

Import file path :

stay src Add a index.html file ( Forgot to say before , Here, make up )  And write the font style and class name

Use cmd Enter the following command To install the plug-in

npm install --save-dev html-webpack-plugin

  Again webpack.config.js Add the following code in

const HtmlWebpackPlugin = require('html-webpack-plugin');
  plugins: [new HtmlWebpackPlugin({

    template: './src/index.html'

  })],

Package resources : 

{
        test: /\.(woff|woff2|eot|ttf|otf)$/i,
        type: 'asset/resource',
        generator: {
					filename: 'fonts/[hash][ext][query]'
				}
 },

After the packaging is completed, it is shown as follows :

  Delete dist All files in the folder or delete them directly dist that will do

 

  Run again

npm run build

After completion, all files deleted before will be automatically generated  

 

  The effect is as follows :

7、 ... and 、devsever

npm install webpack-dev-server --save-dev

  devServer: {
    //  Path after project construction 
    // contentBase: resolve(__dirname, 'build'),
    //  start-up gzip Compress 
    compress: true,
    //  Port number 
    port: 3000,
    //  Open browser automatically 
    open: true,
  },
  mode: 'development'
}

function  

 npx webpack-dev-server

First time yes as well as y 

  After running, it will automatically open the browser for you and render in real time

  Next, you can test the changes css Whether the browser will change when changing the style

 

  It is found here that after packing so much, there is no separate packing css Folder ( Here's the picture ), So next, we will configure the production environment

8、 ... and 、webpack Production environment configuration

install

npm install --save-dev mini-css-extract-plugin

const MiniCssExtractPlugin= require('mini-css-extract-plugin')// extract css In a separate file 

stay plugins Add

  new MiniCssExtractPlugin() 

And use MiniCssExtractPlugin.loader Replace use Inside 'style-loader',

MiniCssExtractPlugin.loader

function npm run build

  In the figure below, you will find that there is a css file , But it didn't css Folder

  At this time, you need to new MiniCssExtractPlugin() Add the following code in

{
    filename:'css/build.css'  //  Create folders and css The name of the document 
  })  

And put the just main.css Delete for  

Pack again :

  You can see that... Has been successfully created

  open index.html It will also display

* Nine 、css Compatibility writing

This is mainly for the packaging of browser compatible styles , for example (display:-webkit-flex style ), Now generally support ie9 Above version , I can't use this expression , But let's demonstrate

First, set the compatible style

install

npm install --save-dev postcss-loader postcss

  remember : Make sure there are no comments , An error will be reported when a comment appears

The code is as follows :

 "browserslist":{
      "development": [
        "last 1 chrome version",
        "last 1 firefox version",
        "last 1 safari version"
      ],
      "production": [
        ">0.02%",
        "not dead",
        "not op_mini all"
      ]
    }

  After the webpack.config.js Add the following code in

  The code is as follows :

install :npm install postcss-preset-env 

{
            loader: 'postcss-loader',
            options: {
              postcssOptions: {
                plugins: [
                  [
                    'postcss-preset-env',  // This needs to be installed npm install postcss-preset-env Otherwise it will not take effect 
                    {
                      //  The other options 
                    },
                  ],
                ],
              },
            },
          },

  package

npm run build 

After packaging, you will find two errors. The reasons are less The comments were not removed from the document

  So here we have to put less Just remove the comments in

Pack again :

npm run build 

The effect is as follows : 

Add a little here , It forgot to say .

Ten 、html Inside img How to package the pictures in the label

stay webpack.config.js Add the following code in :

      {
				test: /\.html$/i,
				loader: "html-loader",
			},

Remember to install plug-ins

npm install --save-dev html-loader

Finally, pack it :

 npm run build 

copyright notice
author[Nanchen_ forty-two],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270126430948.html

Random recommended