Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Step 1: Before installing WebPack, you need your local environment to support Node.js
- Install Node.js (nodejs.org/en/ version 8.11.1) Once installed, NPM (package manager) is automatically generated
- Node-v (test node version number), NPM -v(test NPM version number) —– The purpose of this operation is to test whether the Node environment is built
- Install CNPM (similar to NPM)
- Pros: Its servers are in China, so they’ll run faster
- Address: npm.taobao.org/
- Run the sudo NPM install -g CNPM – registry=registry.npm.taobao.org command on the terminal
Step 2: Two ways to install WebPack
- Run NPM I webpack -g to install webpack globally, so you can use webpack commands globally
- Run NPM I webpack –save-dev in the project root directory to install into the project dependencies
- In version 4.0+, in addition to installing Webpack, you also need to install webpack-cli to run NPM I webpack-cli -g for global installation
Step 3: Create the file project
- Create file directory: myWebpack
- Create two subfolders SRC Dist inside myWebPack
- Place your project content in the SRC folder and create folders CSS, JS, and images, respectively
- Create both index.html and main.js in SRC
- Main.js is mainly used to import JS files so that only one main.js file is loaded in index.html without causing Ajax requests
- The dist folder holds packaged files for distribution (product-level content)
- Using the Webpack tool, place the bundle.js file generated after main.js processing here
- Place your project content in the SRC folder and create folders CSS, JS, and images, respectively
Start project
Problem 1: An error occurs if the advanced ES6 syntax is referenced in the main.js file
-
Cause: Because the browser does not know the advanced JS syntax import, need to use Webpack for processing, Webpack will default this advanced syntax into low-level browser can recognize syntax;
-
Run the webpack entry file path -o output file path to main.js:
// Note that the syntax has changed for version 4.0+, remember to add -o webpack.src \main.js -o. dist\bundle.jsCopy the code
Problem 2: It is too cumbersome to retype the above statement each time the compilation is complete
-
Solution: In the root directory of the project, create a webpack.config.js file and perform the configuration as follows
const path = require('path'); Module.exports = {// entry, which file to pack with webpack entry:'./ SRC /main.js', // exit, Output :{path:path.resolve(__dirname,'dist'),// specify which directory to export the packaged file to. Filename :'bundle.js'// specify the output filename}};Copy the code
Once the files are configured, simply type Webpack at the terminal to pack them
Webpack’s bundle.js file is not stored on the actual physical disk, but is hosted directly in the computer’s memory, so the bundle.js file is not found in the project root directory
Therefore, the bundle.js introduced in index.html should be changed to the following
<script src="/bundle.js"></script>
Copy the code
Problem 3: You have to re-enter the above statement each time, which is simplified but still too cumbersome
- You want to automatically package and compile every time you save
- Solution: Install the webpack-dev-server tool to implement
- Installation steps:
- Run NPM I webpack-dev-server -d
- The usage is exactly the same as webpack
Problem 4: Error running webpack-dev-server!!
- Reason: Webpack-dev-server is installed locally in the project, not globally, and cannot be executed directly on the terminal
- Solution: Configure package.json file as follows (recommended)
{
"name": "mywebpack"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
"test": "echo \"Error: no test specified\" && exit 1"."dev": "webpack-dev-server --open --port 3000 --contentBase src --hot"
//--open is to save and open the browser directly
//--port 3000 Changes the default port number of the browser. The default is localhost:8080
//--contentBase SRC is the SRC file that the browser opens by default, which is the index.html file in the SRC file, not the root directory
//-- Hot reloading. Instead of regenerating the bundle.js file every time, it updates the bundle.js file locally, reducing unnecessary updates and enabling the browser to reload without refreshing
},
"keywords": []."author": ""."license": "ISC"."dependencies": {
"jquery": "^ 3.4.1 track"."webpack-dev-server": "^ 3.8.0." "
},
"devDependencies": {
"webpack": "^ 4.39.1"."webpack-cli": "^ 3.3.6." "}}Copy the code
- The second configuration mode:
-
First do the following configuration in package.json file
"dev": "webpack-dev-server" Copy the code
-
Add the following configuration to webpack.config.js:
-
const webpack = require('webpack');
module.exports = {
devServer: {// This is the second and more complex way to configure the dev-server command parameters
open:true.port:3000.contentBase:'src'.hot:true// Enable hot update step 1
},
plugins: [// Configure the node for the plug-in
new webpack.HotModuleReplacementPlugin()// New a hot updated object step 3]}Copy the code
Step 4: Configure the startup page using the HTML-webpack-plugin
The installation
- Install NPM I html-webpack-plugin -d in terminal
- Import plugins that generate HTML pages in memory in webpack.config.js. Note that plugins must be placed in plugins nodes whenever they are plugins
const htmlWebpackPlugin = require('html-webpack-plugin')
plugins: [// Configure the node for the plug-in
new webpack.HotModuleReplacementPlugin(),// New a hot updated object step 3
new htmlWebpackPlugin({// Create a plug-in that generates HTML pages in memory
template:path.join(__dirname,'./src/index.html'),// Specify a template page that will be generated in memory based on the specified page path
filename:'index.html'// Specify the name of the generated page})]Copy the code
At this point, the generated page source code is as follows. At the bottom of the page, a reference to bundle.js in memory is automatically added, so there is no need to manually add the bundle
<! DOCTYPEhtml>
<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="/bundle.js"></script>
</head>
<body>
<ul>
<li>This is the first LI tag</li>
<li>This is the second LI tag</li>
<li>This is the third LI tag</li>
<li>This is the fourth LI tag</li>
<li>This is the fifth LI tag</li>
<li>This is the sixth LI tag</li>
</ul>
<script type="text/javascript" src="bundle.js"></script></body>
</html>
Copy the code
role
- Automatically generates a memory page based on the specified page in memory
- Automatically appends packaged bundle.js to the page
Step 5: Configure the third-party Loader
Note:
- By default, Webpack can only package files that handle JS types and cannot handle other files that are not JS types
- If you want to process non-JS files, you will need to manually install some suitable third-party loader
Package CSS files:
- Install NPM I style-loader CSS-loader-d
- Add a configuration node module to webpack.config.js
Module :{// This node, Rules :[// Matching rules for all third-party modules {test:/\.css$/,use:['style-loader','css-loader']},// Configure third-party loader rules for processing. CSS files]}Copy the code
- Import the CSS file in main.js at the same time
import './css/index.css'
Copy the code
Package and process less files
- Install NPM I less-loader -d
- Install NPM I less-d
- Add a configuration node module to webpack.config.js
Module :{// This node, Used to configure all third-party module loaders rules:[// All third-party module matching rules {test:/\. Less $/,use:['style-loader','css-loader','less-loader']}s// Configure third-party loader rules for less files]}Copy the code
Package and process SCSS files
- Install NPM I sas-loader -d
- Install CNPM I node-sass -d
- Add a configuration node module to webpack.config.js
Module :{// This node, Used to configure all third-party module loaders rules:[// All third-party module matching rules {test: / \. SCSS $/, use: [' style - loader ', 'CSS - loader', 'sass - loader]} / / configuration processing. Third-party loader SCSS document rules]}Copy the code
conclusion
Index.html is as follows
<! DOCTYPEhtml>
<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>
<! Import all js files into main.js -->
<! -- <script src="main.js"></script> -->
<! -- <script src=".. /dist/bundle.js"></script> -->
<! -- <script src="/bundle.js"></script> -->
</head>
<body>
<ul>
<li>This is the first LI tag</li>
<li>This is the second LI tag</li>
<li>This is the third LI tag</li>
<li>This is the fourth LI tag</li>
<li>This is the fifth LI tag</li>
<li>This is the sixth LI tag</li>
</ul>
</body>
</html>
Copy the code
The main. Js as follows:
import $ from 'jquery'
// Use the import syntax to import the CSS stylesheet
import './css/index.css'
// Import less style
import './css/index.less'
// Import the SCSS style
import './css/index.scss'
$(function(){$('li:odd').css('backgroundColor'.'blue');
$('li:even').css('backgroundColor'.'pink');
})
Copy the code
Webpack. Config. Js as follows
const path = require('path');
const webpack = require('webpack');
const htmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
// entry, indicating which file to pack with WebPack
entry:'./src/main.js'.// export the configuration related to the file
output: {path:path.resolve(__dirname,'dist'),// Specify the directory to output the packaged files to
filename:'bundle.js'// Specify the name of the output file
},
devServer: {// This is the second and more complex way to configure the dev-server command parameters
open:true.port:3000.contentBase:'src'.hot:true// Enable hot update step 1
},
plugins: [// Configure the node for the plug-in
new webpack.HotModuleReplacementPlugin(),// New a hot updated object step 3
new htmlWebpackPlugin({// Create a plug-in that generates HTML pages in memory
template:path.join(__dirname,'./src/index.html'),// Specify a template page that will be generated in memory based on the specified page path
filename:'index.html'// Specify the name of the generated page})].module: {// This node is used to configure all third-party module loaders
rules: [// Match rules for all third-party modules
{test:/\.css$/,use:['style-loader'.'css-loader']},// Configure third-party loader rules for handling. CSS files
{test:/\.less$/,use:['style-loader'.'css-loader'.'less-loader']},// Configure third-party Loader rules for processing. Less files
{test:/\.scss$/,use:['style-loader'.'css-loader'.'sass-loader']}// Configure third-party loader rules for handling. SCSS files]}};Copy the code
Package. The json as follows
{
"name": "MyProgram_webpack"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
"test": "echo \"Error: no test specified\" && exit 1"."dev2": "webpack-dev-server --open --port 3000 --contentBase src --hot"."dev": "webpack-dev-server"
},
"keywords": []."author": ""."license": "ISC"."dependencies": {
"jquery": "^ 3.4.1 track"."webpack-dev-server": "^ 3.8.0." "
},
"devDependencies": {
"css-loader": "^ 3.2.0"."html-webpack-plugin": "^ 3.2.0"."less": "^ 3.9.0"."less-loader": "^ 5.0.0"."sass-loader": "^ 7.2.0"."style-loader": "^ 1.0.0"."webpack": "^ 4.39.1"."webpack-cli": "^ 3.3.6." "}}Copy the code
Use NPM run dev every time you start it