Webpack Core Concepts:
- Entry: the entrance
- Everything in Webpack is a Module
- Chunk: Code base. A Chunk is composed of more than ten modules for code merging and splitting
- Loader: module converter, used to convert the original content of a module into new content as required
- Plugin: Extension that injects extension logic at specific points in the WebPack build process to change the build result or do what you want
- Output: Output results
Webpack process:
When webpack starts, it recursively resolves all modules that Entry depends on, starting from the Module configured in the Entry. When a Module is found, the system finds the corresponding conversion rule according to the configured Loader, converts the Module, and then resolves the Module dependent on the current Module. These modules are grouped by Entry, and an Entry and all its dependent modules are assigned to a group called a Chunk. Preferably Webpack will convert all chunks into files for output. Webpack executes the logic defined in the Plugin at appropriate times throughout the process.
Let’s start from scratch with a Webpack configuration that supports packing images,CSS,LESS,SASS, ES6/ES7 and JSX syntax, and compression of code.
More articles can be read: github.com/YvetteLau/B…
1. Minimal WebPack configuration
First initialize NPM and install webPack dependencies:
npm init -y
npm install --save-dev webpack webpack-cli
Copy the code
Configure the webpack.config.js file as follows:
const path = require('path');
module.exports = {
entry: path.resolve(__dirname, 'src/index.js'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'.publicPath: '/'}}Copy the code
Note: The CDN address is configured when publicPath goes online.
Package with commands:
webpack --mode production
Copy the code
It can also be configured into the scripts field in package.json.
The entry file is SRC /index.js, and the output is packaged to dist/bundle.js.
2. Use template HTML
The html-webpack-plugin can specify the template template file, which will generate the HTML file in the output directory and import the packaged JS.
Install dependencies:
npm install --save-dev html-webpack-plugin
Copy the code
Add plugins to webpack.config.js:
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
/ /... other code
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'src/index.html')]}})Copy the code
HtmlWebpackPlugin also has some other parameters, such as title(the title of the HTML),minify(whether to compress or not),filename(the filename of the HTML generated in dist), etc
3. The configuration webpack – dev – server
Webpack-dev-server provides a simple Web server and real-time hot update capability
Install dependencies:
npm install --save-dev webpack-dev-server
Copy the code
Add devServer configuration to webpack.config.js:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
/ /... other code
devServer: {
contentBase: './dist'.port: '8080'.host: 'localhost'}}Copy the code
Add to the scripts field of package.json:
webpack-dev-server --mode development
Copy the code
After that, we can start the service with NPM run dev.
More webpack dev – the knowledge of the server, please visit: webpack.js.org/configurati…
4. Supports loading CSS files
CSS files can be converted to JS file types by using different style-loader and CSS-loader.
Install dependencies:
npm install --save-dev style-loader css-loader
Copy the code
Add loader configuration in webpack.config.js.
module.exports = {
//other code
module: {
rules: [{test: /\.css/.use: ['style-loader'.'css-loader'].exclude: /node_modules/.include: path.resolve(__dirname, 'src'}]}}Copy the code
The following parameters can be configured for loader:
- Test: a regular expression that matches the extension of the processing file
- Use: the name of the loader
- Include /exclude: Manually specify the required folder or exclude the folder that does not need to be processed
- Query: Provides additional setup options for the Loader
To pass parameters to loader, use use+loader, for example:
module.exports = {
//other code
module: {
rules: [{use: [{
loader: 'style-loader'.options: {
insertAt: 'top'}},'css-loader'].//....}}}]Copy the code
5. Support loading pictures
- File-loader: Resolves the problem of importing image paths in files such as the CSS
- Url-loader: If an image is smaller than limit, the Base64 encoding is used. If an image is larger than limit, file-loader is used to copy the image
If you want images to be stored in a separate directory, you need to specify an outputPath
Install dependencies:
npm install --save-dev url-loader file-loader
Copy the code
Add loader configuration in webpack.config.js (added in array of module.rules).
module.exports = {
//other code
module: {
rules: [{test: /\.(gif|jpg|png|bmp|eot|woff|woff2|ttf|svg)/.use: [{loader: 'url-loader'.options: {
limit: 8192.outputPath: 'images'}}]}}Copy the code
6. Supports less and SASS compilation
Some front-end colleagues may be used to writing CSS in less or Sass, so they need to configure it in WebPack as well.
Install the corresponding dependencies:
npm install --save-dev less less-loader
npm install --save-dev node-sass sass-loader
Copy the code
Add loader configuration in webpack.config.js (in the module.rules array).
module.exports = {
//other code
module: {
rules: [{test: /\.less/.use: ['style-loader'.'css-loader'.'less-loader'].exclude: /node_modules/.include: path.resolve(__dirname, 'src')}, {test: /\.scss/.use: ['style-loader'.'css-loader'.'sass-loader'].exclude: /node_modules/.include: path.resolve(__dirname, 'src'}]}}Copy the code
7. ES6/ES7/JSX can be escaped
ES6/ES7/JSX escapes require a dependency on Babel and support decorators.
npm install --save-dev @babel/core babel-loader @babel/preset-env @babel/preset-react @babel/plugin-proposal-decorators @babel/plugin-proposal-object-rest-spread
Copy the code
Add loader configuration in webpack.config.js (in the module.rules array).
module.exports = {
//other code
module: {
rules: [{test: /\.jsx? $/.use: [{loader: 'babel-loader'.options: {
presets: ['@babel/preset-env'.'@babel/react'].plugins: [["@babel/plugin-proposal-decorators", { "legacy": true}]]}}],include: path.resolve(__dirname, 'src'),
exclude: /node_modules/}}},]Copy the code
8. Compress the JS file
Install dependencies:
npm install --save-dev uglifyjs-webpack-plugin
Copy the code
Add the optimization configuration to webpack.config.js
const UglifyWebpackPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
//other code
optimization: {
minimizer: [
new UglifyWebpackPlugin({
parallel: 4}}})]Copy the code
9. Separate CSS(if CSS file is large)
Because CSS downloads and JS can be done in parallel, when an HTML file is large, the CSS can be extracted and loaded separately
npm install --save-dev mini-css-extract-plugin
Copy the code
Add plugins in webpack. Config. Js configuration, and amend the ‘style – loader to {loader: MiniCssExtractPlugin loader}.
CSS is packaged in a separate directory, then configure filename.
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
//other code
module: {
rules: [{test: /\.css/.use: [{ loader: MiniCssExtractPlugin.loader}, 'css-loader'].exclude: /node_modules/.include: path.resolve(__dirname, 'src')}, {test: /\.less/.use: [{ loader: MiniCssExtractPlugin.loader }, 'css-loader'.'less-loader'].exclude: /node_modules/.include: path.resolve(__dirname, 'src')}, {test: /\.scss/.use: [{ loader: MiniCssExtractPlugin.loader }, 'css-loader'.'sass-loader'].exclude: /node_modules/.include: path.resolve(__dirname, 'src')},]},plugins: [
new MiniCssExtractPlugin({
filename: 'css/[name].css'}})]Copy the code
10. Compress the CSS file
Install dependencies:
npm install --save-dev optimize-css-assets-webpack-plugin
Copy the code
Add configuration in Optimization in webpack.config.js
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
module.exports = {
//other code
optimization: {
minimizer: [
new OptimizeCssAssetsWebpackPlugin()
]
}
}
Copy the code
11. Clear the output directory before packing
npm install --save-dev clean-webpack-plugin
Copy the code
Add plugins to webpack.config.js
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
//other code
plugins: [
new CleanWebpackPlugin()
]
}
Copy the code
At this point, the WebPack configuration is basically sufficient.
Complete webpack.config.js and package.json files
Webpack. Config. Js file:
const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');
const UglifyWebpackPlugin = require('uglifyjs-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
module.exports = {
entry: path.resolve(__dirname, 'src/index.js'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'.publicPath: '/'
},
devServer: {
contentBase: './dist'.port: '8080'.host: 'localhost'
},
module: {
rules: [{test: /\.jsx? $/.use: [{loader: 'babel-loader'.options: {
presets: ['@babel/preset-env'.'@babel/react'].plugins: [["@babel/plugin-proposal-decorators", { "legacy": true}]]}}],include: path.resolve(__dirname, 'src'),
exclude: /node_modules/
},
{
test: /\.css/.use: [{ loader: MiniCssExtractPlugin.loader}, 'css-loader'].exclude: /node_modules/.include: path.resolve(__dirname, 'src')}, {test: /\.less/.use: [{ loader: MiniCssExtractPlugin.loader }, 'css-loader'.'less-loader'].exclude: /node_modules/.include: path.resolve(__dirname, 'src')}, {test: /\.scss/.use: [{ loader: MiniCssExtractPlugin.loader }, 'css-loader'.'sass-loader'].exclude: /node_modules/.include: path.resolve(__dirname, 'src')}, {test: /\.(gif|jpg|png|bmp|eot|woff|woff2|ttf|svg)/.use: [{loader: 'url-loader'.options: {
limit: 1024.outputPath: 'images'}}]}]},optimization: {
minimizer: [
new UglifyWebpackPlugin({
parallel: 4
}),
new OptimizeCssAssetsWebpackPlugin()
]
},
plugins: [
new htmlWebpackPlugin({
template: path.resolve(__dirname, 'src/index.html'),}),new MiniCssExtractPlugin({
filename: 'css/[name].css'
}),
new CleanWebpackPlugin()
]
}
Copy the code
Package. Json file:
{
"name": "webpk"."version": "1.0.0"."description": ""."main": "webpack.config.js"."scripts": {
"test": "echo \"Error: no test specified\" && exit 1"."build": "webpack --mode production"."dev": "webpack-dev-server --mode development"
},
"keywords": []."author": ""."license": "ISC"."devDependencies": {
"@babel/core": "^ 7.4.0"."@babel/plugin-proposal-decorators": "^ 7.4.0"."@babel/plugin-proposal-object-rest-spread": "^ 7.4.0"."@babel/preset-env": "^ 7.4.1"."@babel/preset-react": "^ 7.0.0." "."babel-loader": "^ 8.0.5"."clean-webpack-plugin": "^ 2.0.1." "."css-loader": "^ 2.1.1"."file-loader": "^ 3.0.1." "."html-webpack-plugin": "^ 3.2.0"."less": "^ 3.9.0"."less-loader": "^ 4.1.0." "."mini-css-extract-plugin": "^ 0.5.0"."node-sass": "^ 4.11.0"."optimize-css-assets-webpack-plugin": "^ 5.0.1." "."sass-loader": "^ 7.1.0"."style-loader": "^ 0.23.1"."uglifyjs-webpack-plugin": "^ 2.1.2"."url-loader": "^ 1.1.2." "."webpack": "^ 4.29.6"."webpack-cli": "^ 3.3.0"."webpack-dev-server": "^ 3.2.1." "
},
"dependencies": {
"react": "^ 16.8.4"."react-dom": "^ 16.8.4"."react-redux": "^ the 6.0.1." "."redux": "^ 4.0.1." "}}Copy the code
More loader and the parameters of the plugin you can refer to: www.webpackjs.com/loaders/ www.webpackjs.com/plugins/
If you have other webPack configuration requirements, please leave a comment
Thank you for spending your precious time reading this article. If this article gives you some help or inspiration, don’t be too sparing with your likes and stars. Your praise is definitely the biggest motivation for me to move forward. Github.com/YvetteLau/B…
Thanks for pointing out, add reference link
- Webpack official documentation