webpack Basics
1. Front end Engineering
Concept: in the development of enterprise level front-end projects, standardize and standardize the tools, technologies, processes and experience required for front-end development.
1.1. Actual front-end development
-
Modularization: modularization of js, CSS and resources (these resources are introduced into js rather than directly placed in html)
-
Componentization: reuse the existing UI structure, style and behavior
-
Standardization: directory structure division, coding standardization, interface standardization, document standardization, Git branch management
-
Automation: automated build, automated deployment, automated testing
1.2 advantages:
-
The front-end development has its own system, with a set of standard development schemes and processes
1.3 solution
-
Early front end engineering solutions
-
grunt
-
gulp
-
-
Current mainstream front-end engineering solutions
-
webpack(https://www.webpackjs.com)
-
parcel
-
2. Basic use of webpack
2.1. Create list interlaced color change items
-
Project initialization
-
Create a new project blank directory and run the npm init -y command to initialize the package management configuration file package.json
-
Enter the new blank directory, enter cmd in the address bar, and then enter npm init -y
-
This is the generated package.json file
-
-
New src source directory
-
Create new SRC - > index.html and Src - > index.js script files
-
Initialize the basic structure of the first business
-
Run the npm install jquery -S command to install JQuery
-
-S is short for -- save, indicating that the package to be installed is recorded under the dependencies node (the node here refers to the node under package.json)
-
-
Import JQuery through the Bergamot mode of ES6 module to realize the color change effect of list interlacing
-
Basic structure of html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="./index.js"></script> </head> <body> <div> <ul> <li>This is the first one li</li> <li>This is the second li</li> <li>This is the third li</li> <li>This is the fourth li</li> <li>This is the fifth li</li> <li>This is the sixth li</li> <li>This is the seventh li</li> <li>This is the eighth li</li> <li>This is the ninth li</li> </ul> </div> </body> </html>
JS using ES6:
// 1. Import JQuery using ES6 import $ from 'jquery' // 2. Define the JQuery entry function $(function({ // 3. Realize parity line color change, $('li:odd').css('background-color','red'), $('li:even').css('background-color','green') }))
There is a syntax problem: the page cannot be interlaced and changed color. You need to use webpack to solve it.
2.2. Installing webpack
-
Install command: ` NPM install webpack@5.42.1 webpack- cli@4.7.2 -D``
-
`-D is short for -- save dev, which means that the package is recorded under the devDepdependencies node, that is, it is only used in the development phase
-
If npm cannot be used, cnpm can be used
-
2.3. Configure webpack
-
In the root directory of the project, create a webpack configuration file named webpack.config.js, and initialize the following basic configuration
// Use the export syntax in node.js to export a webpack configuration object module.exports={ mode: 'development' // Mode is used to specify the construction mode. The optional values are development and production }
-
Under the scripts node of package.json, add the dev script as follows
"scripts":{ "dev": "webpack" // Scripts under the script node can be executed through npm run, such as npm run dev }
-
Run the npm run dev command in the terminal to start the webpack to package and build the project, which is actually the action of webpack
-
After the webpack is packaged, a dist folder will be generated. There is a main.js under the folder. This is the browser compatible version of the webpack after packaging. This is uncompressed main.js. If you want to compress it, change the construction mode to productioin
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <!-- <script src="./index.js"></script> --> <script src="../dist/main.js"></script> <!-- Changed file --> </head> <body> <div> <ul> <li>This is the first one li</li> <li>This is the second li</li> <li>This is the third li</li> <li>This is the fourth li</li> <li>This is the fifth li</li> <li>This is the sixth li</li> <li>This is the seventh li</li> <li>This is the eighth li</li> <li>This is the ninth li</li> </ul> </div> </body> </html>
2.4 execution steps of webpack
-
After running npm run -dev, the webpack of dev under the scripts node will be found first
-
Before running the webpack, the webpack.config.js will be scanned first
2.5. webpack agreement and custom packaging path
-
Default contract in webpack
-
In versions 4.x and 5.x, there are the following default conventions
-
The default package entry file is SRC - > index.js. By default, if there is no corresponding directory and file, an error will be reported
-
The default output file path is dist - > main.js
-
You can modify the default packaging convention in webpack.config.js
-
-
Custom packaged entry and exit
-
In the webpack.config.js configuration file, specify the packaged entry through the entry node and the packaged exit through the output node,
-
__dirname refers to the project directory, that is, the directory at the same level as src.
-
const path = require('path') // Import modules in node.js that are dedicated to operating paths // Use the export syntax in node.js to export a webpack configuration object module.exports={ mode:'development',// Mode is used to specify the construction mode. The optional values are development and production, entry: path.join(__dirname,'./src/index.js'), // Path of package entry file, customized output:{ path: path.join(__dirname,'./dist'),// Output file storage path, custom filename: 'bundle.js' // Name of output file, custom } }
2.6. Use of webpack plug-in
-
Whenever the source code of webpack dev server is modified, webpack will automatically package and build the project
-
Installation: NPM install webpack dev- server@3.11.2 -D. If it is not successful, use cnpm install webpack cli -- save dev
-
Configuration: add "dev":"webpack server" or "dev":"webpack serve" under the scripts node
-
Run npm run dev again
-
The webpack server will regenerate the file in the form of cache. In the project root directory, this cache file should be introduced when referencing the file
-
-
Visit localhost:8080 in the browser to see the effect of automatic packaging
-
-
HTML webpack plugin can customize the content of the index.html page through this plug-in (that is, copy index.html to the project root directory and inject bundle.js)
-
Installation: NPM install HTML webpack- plugin@5.3.2 -D
-
Configuration: as shown in the following code
-
Just run npm run dev
-
/** html-webpack-plugin to configure */ // 1. Import the HTML plug-in to get a constructor const HtmlPlugin = require('html-webpack-plugin') // 2. Create an instance object of the HTML plug-in const htmlPlugin = new HtmlPlugin({ template: './src/index.html', // Specify the storage path of the original file filename: './index.html' // Specifies the storage path of the generated file, which is a cache in memory }) module.exports={ mode:'development',// Mode is used to specify the construction mode. The optional values are development and production, plugins: [htmlPlugin] // 3. Make the htmlPlugin plug-in effective through the plugins node }
2.7. devServer node
-
Function: automatically open the browser after running npm run dev
-
Configuration: add the following configuration in module.exports under webpack.config.js:
devServer:{ open: true, // After the initial packaging is completed, the browser opens automatically host: '127.0.0.1', // Host address used for real-time packaging port: 80 // Port number used for real-time packaging }
2.8,Loader
In the actual development process, webpack can only package modules ending in js suffix by default. Other modules ending in non js suffix cannot be processed by webpack by default. You need to call loader loader to package normally, otherwise an error will be reported.
-
Role: assist webpack in packaging and processing specific file modules, such as:
-
css loader can package and process. css related files
-
less loader can package and process. less related files
-
Babel loader can package and handle Advanced js syntax that webpack cannot handle
-
-
All css stylesheets written are import ed in the corresponding. js
-
usage method:
Processing CSS files
-
Run NPM I style- loader@3.0.0 css- loader@5.2.6 -D. Install the loader that handles CSS files
-
In the rules array of module.exports in webpack.config.js, add the loader rule as follows
-
test indicates the matching file type, and use indicates the corresponding loader to be called
-
The order of loader s specified in the use array is fixed
-
The calling sequence of multiple loader is called from the back.
-
/** In module.exports */ module: { rules: [ {test:/\.css$/,use:['style-loader','css-loader']} ] }
Processing less files
-
Run NPM I less- loader@10.0.1 less@4.1.1 -D. Install the loader that handles less files
-
In the rules array of module.exports in webpack.config.js, add the loader rule as follows
module: { rules: [ {test:/\.css$/,use:['style-loader','css-loader']}, {test:/\.less$/,use:['style-loader','css-loader','less-loader']} // There are several types of files, just add a few. ] }
Processing picture files
-
Add img tag in index.html: < img SRC = "" ALT = "" class = "box" >
-
Reference the picture in index.js and act on the src attribute in the img tag
// Import the picture and get the picture file // Dynamic assignment of src to Img tag import img from '../images/1.jpg' $('.box').attr('src',img);
-
Run NPM I URL- loader@4.1.1 file- loader@6.2.0 -D. Install the loader that handles picture files
-
In the rules array of module.exports in webpack.config.js, add the loader rule as follows
-
? Then comes the parameter of loader
-
limi is used to specify the size of the picture in bytes
-
Only images smaller than or equal to the limit size will be converted to base64 format images
-
module: { rules: [ {test:/\.css$/,use:['style-loader','css-loader']}, // Handling CSS {test:/\.less$/,use:['style-loader','css-loader','less-loader']}, // Deal with Less {test:/\.jpg|png|gif$/,use:['url-loader?limit=2048']}, // Processing pictures ] }
Handling advanced JS syntax
-
Define a js that webpack cannot handle
// 1. Define a decorator named info function info(target){ // target is the decorator // 2. Add static attribute info for the target target.info = 'Person info' } // 3. Apply info decorator for Person class @info class Person{} // 4. Print the static attribute info of Person console.log(Person.info)
-
Run cnpm i babel-loader@8.2.2 @babel/core@7.14.6 @babel/plugin-proposal-decorators@7.14.5 -D. Install the loader that handles js advanced syntax files
-
Add loader rule: {test: / \. JS /, use: 'Babel loader', exclude: '/ node_modules /'}
-
Create a configuration file named ` babel.config.js in the project root directory and add plugins:`
/** babel.config.js */ module.exports ={ plugins: [ [ "@babel/plugin-proposal-decorators", { "legacy": true } ] ] }
2.9 release and launch
The current pages index.html and bundle.js are in memory and cannot be published directly
-
Under the scripts node in the package.json file, add the build command: ` "build":"webpack --mode production"
-
--Mode is a parameter item used to specify the running mode of webpack. Production represents the production environment. It compresses the code and optimizes the performance of the packaged files
-
The parameter item specified by -- mode will override the mode option in webpack.config.js, that is, the mode here has high priority
-
Generate new files through npm run build. If the picture is less than the limit, the picture will not be copied, otherwise the picture will be copied.
"scripts": { "dev": "webpack server", "build":"webpack --mode production" // Production can be specified },
-
Put the generated js files in the js folder
module.exports={ mode:'development',// Mode is used to specify the construction mode. The optional values are development and production, entry: path.join(__dirname,'./src/index.js'), // Path of package entry file, customized output:{ path: path.join(__dirname,'./dist'),// Output file storage path, custom filename: 'js/bundle.js' // Name of output file, custom } }
-
Put the picture files in the image directory: modify the URL loader configuration item in ` webpack.config.js, as follows:
/***********The first way to write***************/ module: { rules: [ // CSS processing {test:/\.css$/,use:['style-loader','css-loader']}, // less file processing {test:/\.less$/,use:['style-loader','css-loader','less-loader']}, // Process the image and modify the URL loader configuration { test:/\.jpg|png|gif$/, use:{ loader:'url-loader', options: { limit:2048, outputPath: 'image' // Add picture directory output } } }, // js advanced syntax processing {test: /\.js/, use: 'babel-loader', exclude: '/node_modules/'}, ] } /***********The second way to write***************/ module: { rules: [ {test:/\.css$/,use:['style-loader','css-loader']}, // Handling CSS {test:/\.less$/,use:['style-loader','css-loader','less-loader']}, // Deal with Less // When configuring URL loader, multiple parameters are separated by the & symbol {test:/\.jpg|png|gif$/,use:['url-loader?limit=2048&outputPath=image']}, // Processing pictures ] }
-
The dist folder is automatically deleted before publishing
-
Installation: NPM install clean webpack- plugin@3.0.0 -D
-
Configure plug-ins:
-
// 1. Generate class // The brace on the left is the deconstruction assignment const {CleanWebpackPlugin} = require('clean-webpack-plugin') // 2. Generate class objects const cleanDist = new CleanWebpackPlugin() // 3. Add plug-ins plugins: [htmlPlugin,cleanDist]
2.10,source Map
The Source Map generated in the development environment records the location of the generated code. This will cause the number of error lines in the run to be inconsistent with the number of lines in the source code
-
Exposed original code and line number:
module.exports={ mode: 'development', // Eval source map can only be used in "development mode", not in "production mode", which will expose the original code // This setting can ensure that the original code location is consistent with the code location generated by the production environment devtool: 'eval-source-map' }
-
Expose line numbers only
module.exports={ mode: 'development', // This setting can ensure that the original code location is consistent with the code location generated by the production environment devtool: 'nosources-source-map' }
2.11. Resource import
-
Use @ to represent the src source code directory and search from the outside to the inside; Do not use.. /.. /... To search from the inside out, such as: import XXX from '@/js/xxx.js'
-
Add the resolve node of module.exports in webpack.config.js
resolve: { alias: { // Tell webpack that in the code written by the programmer, the @ symbol represents the src directory '@' : path.join(__dirname,'/src/') } }