Webpack basic tutorial
1. Basic use
2. Use HtmlWebpackPlugin
3. Use WebpackDevServer
4. Compile ES6 code
Basic use
Create a package.json file, open the command line tool and run
npm init -y
Install webpack and webpack-cli
npm install webpack webpack-cli --save-dev
Create a src folder in the root directory, then create an index.js file in it, and write a simple code hello word
console.log("hello word")
Create a configuration file webpack.config.js in the root directory
const path = require('path')
module.exports = {
mode: 'development',
entry: path.join(__dirname, 'src', 'index.js'),
output: {
path: path.join(__dirname, 'src', 'dist'),
filename: 'bundle.js'
}
}
Modify package.json file scripts command
"build": "webpack"
Run package npm run build
Using HtmlWebpackPlugin
Installation
npm install html-webpack-plugin --save-dev
Modify the configuration file webpack.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'development',
entry: path.join(__dirname, 'src', 'index.js'),
output: {
path: path.join(__dirname, 'src', 'dist'),
filename: 'bundle.js'
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, 'src', 'index.html'),
filename: 'index.html'
})
]
}
Create a new index.html in the src directory
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
</html>
Run the package again npm run build
Using WebpackDevServer
Installation
npm install webpack-dev-server --save-dev
Modify the configuration file webpack.config.js
devServer: {
port: 8000,
static: path.join(__dirname, 'dist')
}
Modify package.json file scripts command
"dev": "webpack-dev-server"
Run npm run dev
Visit http://localhost:8000/
Modify the index.html file, click Save, and the page will change
Compile ES6 code
Write a piece of ES6 code in the index.js file
const sum = (num1, num2) => {
return num1 + num2
}
console.log(sum(1,2))
By viewing the source code, we can find that ES6 is still used. In order to be compatible with lower version browsers, conversion is required.
Install babel
npm install @babel/core @babel/preset-env babel-loader --save-dev
Create the configuration file .babelrc in the root directory
{
"presets": ["@babel/preset-env"]
}
修改配置文件 webpack.config.js
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
include: path.join(__dirname, 'src'),
exclude: /node_modules/
}
]
},
By looking at the source code, you find that the ES6 code has become ES5.
Since then, you have basically learned webpage