Check that Node, NPM, and NPX are installed correctly
node --version
npm --version
npx --version
Copy the code
Webpack is a front-end resource builder, a static module packer
Webpack official documentation at https://webpack.js.org/guides/installation/
From WebPack’s point of view, all resource files in the front end are treated as modules. It will carry out static analysis according to the dependencies of modules and generate the corresponding static resources.
The biggest difference between Webpack and Gulp is the packaging process
Build tools such as Grunt and Gulp are packaged by traversing source files – > matching rules – > packaging. The whole process is packaged based on file stream and cannot be loaded on demand.
Webpack starts from the entry file, introduces related modules by loading modules – > parsing modules – > packaging, the whole process is based on modular packaging and support on demand loading, but also in the process of execution to do some targeted optimization operations.
Five core concepts of Webpack 1. Entry: Entry indicates the file from which webpack starts to pack and builds internal dependencies. 2. Output: Output represents where the resource bundles Output of Webpack go and how to name them. 3. Loader: Loader allows Webpack to handle resources that are not JavaScript files (Webpack itself only understands JavaScript) 4. Plugins: Plugins can be used to perform a wider range of tasks, from packaging optimization and compression to redefining variables in the environment. 5. Mode: Mode means that Webpack uses the configuration of the corresponding ModeCopy the code
Webpack first requires the support of the local node.js environment
1. Configure the Node.js environment installation and configuration instructions
www.runoob.com/nodejs/node…
2. Initialize a WebPack project
Command line writing
Install webpack globally: NPM install webpack -g
Install the appropriate version of Webpack: NPM install [email protected]
Delete webpack globally: NPM uninstall webpack -g
Initialize the project
Json and package-lock.json files are automatically generated after CD goes to the project folder: NPM init -y
Install webpack
Global installation: Run through WebPack
NPM I webpack webpack-cli -d or NPM install -d webpack-cli, the node_modules folder is automatically generated
3. Plugin packages for WebPack
Consider the correspondence between the Webpack version and the plug-in version. Otherwise there will be a headache.
To view the version of Webpack and WebPack-CLI, open package.json in the editor
The corresponding mainstream plugin function www.jianshu.com/p/facfdf413…
Production plug-ins: –save-dev
Common plug-ins include: webpack-cli: used to run webpack CSs-loader on the CLI: used to load CSS file style-loader: Use <style> to inject csS-loader internal styles into our HTML page file-loader\url-loader: 1. Url-loader depends on file-loader. 2. Otherwise, file-loader is used to increase the loading speed of the browser. 3, url-loader is better than file-loader so use both plugins unless url-loader does not set limit, which is a waste of time and not good. Html-webpack-plugin: automatically generates the index. HTML file clean-webpack-plugin: Each packaging will clean up the legacy files that were packed beforeCopy the code
4. Basic project examples
1. Create a basic directoryCopy the code
Create a new SRC folder under the root directory. The SRC folder is divided into js, CSS, and img folders. Create an index.js file inside the js folder.
Create a new dist folder in your root directory and create a new index.html folder
Write down some test code in a separate file
// index.js
function init(){
console.log('hello webpack');
}
init();
Copy the code
// index.html<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial-scale =1.0"> <title>webpack</title> </head> <body> <script SRC ="main.js"></script> </body> </ HTML >Copy the code
2. Perform initial packagingCopy the code
Next, execute the NPX webpack command. After running this command, you will have a main.js file under the dist folder, which contains the packing and consolidation of the execution results of the files in the SRC folder.
At this point, WebPack will provide a default configuration, which is not enough, we also need to customize the configuration file to meet our different requirements for the scenario.
3. Customize the basic configuration fileCopy the code
Create a new webpack.config.js file in the root directory and write down some basic configurations, including the five core configurations for WebPack
// resolve the method used to concatenate absolute paths
const { resolve } = require('path')
module.exports = {
// The relative position of the entry file
entry: './src/js/index.js'.output: {
// Generated interface file
filename: 'main.js'.// The generated bundle.js file is placed in the dist file
path: resolve(__dirname, 'dist')},/* development: production */
// Mode configuration
mode: 'development',}Copy the code
Now let’s use NPX WebPack again to rebuild, and once packaged, the effect is the same
4. NPX webpack commandCopy the code
There are three ways to run the command line:
// No webpack.cofig.js file is used when the default configuration file is used
npx webpack index.js // The interface file is index.js
// when there is a webpack.cofig.js file
npx webpack
// have the webpack.cofig. Js file and complete the corresponding configuration
npm run build
Copy the code
NPX is run based on the local webpack. We can also set a shortcut, as shown in the third command, by adding an NPM script to package.json, i.e. adding a configuration “build: “webpack” to the scripts of package.json
{
"name": "webpackcase"."version": "1.0.0"."description": ""."private": true."scripts": {
"bundle": "webpack"// The changed part
},
"author": ""."license": "ISC"."dependencies": {
"webpack": "^ 4.37.0"."webpack-cli": "^ 3.3.6." "}}Copy the code
5. Common non-javascript resource management Loader and various plug-ins
Webpack can use the loader to handle resources that are not JavaScript files
Loader-related configurations need to be written in module, such as:
module: {
rules: [
// This is the loader configuration]}Copy the code
1. Handle CSS resource plug-ins' style-loader 'and' CSS-loader 'Copy the code
Create an index. CSS file in the CSS folder in the SRC directory and write some random test code
html,body{
background-color: #f5f5f5;
}
Copy the code
This is the physical structure of the project
Loading CSS files requires the introduction of new plug-ins style-loader and CSS-loader
npm i -D style-loader css-loader
Copy the code
Write down the corresponding configuration in module.rules
Repackage the NPM Run build after configuration
2. Handle image resource plug-ins' url-loader 'and' file-loader 'Copy the code
Feel free to write some test code under the index.css file
.box1{
width: 100px; height: 100px; background: url(.. /img/testImg.PNG) no-repeat; background-size:100% 100%;
}
Copy the code
Write an empty div in dist/index.html
<div class="box1"></div>
Copy the code
Loading img files requires the introduction of new plugins url-loader and file-loader
npm i -D url-loader file-loader
Copy the code
Write down the corresponding configuration in module.rules
{
test: /\.(jpg|png|gif|PNG)$/,
loader: 'url-loader',},Copy the code
The packed file will be renamed with hash value. In this case, we can configure other parameters of url-loader such as:
{
test: /\.(jpg|png|gif|PNG)$/,
loader: 'url-loader'.options: {
If the image size is less than 8KB, it will be processed as base64
// Advantages: Reduce the number of requests and reduce server stress
// Disadvantages: Larger image size, slower file request speed
limit: 8 * 1024.// Controls the length of the named character
name:'[hash:10].[ext]',}},Copy the code
3. Deal with font resourcesCopy the code
— — — — — — — — — — — — — — — – to write — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
4. Output single page (generate index.html) plugin 'html-webpack-plugin'Copy the code
To do this we need to manually create an index.html file in the dist file and import the output main.js manually. But index.html should also be automatically generated by configuration
Here we need to introduce a plug-in called htMl-webpack-plugin
npm i -D html-webpack-plugin
Copy the code
Modify the configuration file webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: {... },output: {... },module:{
...
},
plugins: [
// Plugins are configured in detail
new HtmlWebpackPlugin({
// copy this./ SRC /index.html and automatically import all the resources that are packaged as output
template: './src/index.html'}),].mode: 'development',}Copy the code
Delete dist and repackage it, we’ll find an extra index.html file in dist, and automatically introduce main.js
5. The clean - webpack - plugin plug-inCopy the code
Configuration:
const {CleanWebpackPlugin} = require('clean-webpack-plugin')
module.exports = {
/ /... Omit other configurations
plugins: [new CleanWebpackPlugin()]
}
Copy the code
In this paper, the source: blog.csdn.net/mollyGO/art…