Webpack5 configuration manual (starting from 0)
Webpack installation sequence
1. 'NPM init -y', initialize package.json 2. Create SRC source directory 3. Create index. HTML 4. 'yarn add webpack webpack-cli', install webpack package 5. 6. 'yarn add webpack-dev-server', install the tool that supports automatic project packaging. Configure 7. 'yarn add html-webpack-plugin', install the plug-in to generate preview pages, and configure 8. 'yarn add style-loader CSS-loader', install the loader to process CSS files Less-loader less ', install loader that processes less files. 10. 'yarn add sass-loader node-sass', install loader that processes SCSS files Postcss-loader postCSS-preset -env autoprefixer ', configure postCSS to automatically add compatible PREfixes of CSS (optional) 12. 'yarn add url-loader 'yarn add html-loader', install and process the image and font files in the CSS files. 14. 'yarn add @babel/core babel-loader The first 3 are required for @babel/preset-env, @babel/plugin-transform-runtime @babel/plugin-proposal-class-properties' Then look at the plug-in installation code below.Copy the code
yarn add html-webpack-plugin yarn add style-loader css-loader yarn add less-loader less yarn add sass-loader node-sass Yarn add url-loader file-loader yarn add html-loader yarn add @babel/core babel-loader@babel /preset-env The first three are mandatory, @babel/ plugin-transform-runtime@babel /plugin-proposal-class-properties yarn add postcss postCSs-loader The first 3 are mandatory postCSs-preset -env, Postcss-cssnext YARN add mini-css-extract-plugin yarn add optimize- CSS-assets -webpack-plugin yarn add eslint Eslint-loader eslint-webpack-plugin YARN add ESlint-config-airbnb-base or eslint-config-airbnb or vue esLint yarn add clean-webpack-pluginCopy the code
usenpx babel-upgrade
Update all plug-ins for Babel to the latest version for compatibility
Configure it in.babelrc, or add it directly in package.json
{
"presets": ["@babel/preset-env"],
"plugins": [
"@babel/plugin-transform-runtime",
"@babel/plugin-proposal-class-properties"
]
}
Copy the code
Configure plug-ins in webpack.config.js
const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: 'development'.entry: path.join(__dirname, './src/main.js'),
output: {
path: path.join(__dirname, './dist'),
filename: 'bundle.js',},/ / the plugin
plugins: [
// html
new htmlWebpackPlugin({
template: path.join(__dirname, './src/index.html'),
filename: 'index.html',}).Clear dist before packing
new CleanWebpackPlugin(),
],
/ / Loaders
module: {
rules: [{// test Sets the file type to be matched. Regular files are supported
test: /\.css$/.// use Specifies the loader to be invoked for the file type
use: ['style-loader'.'css-loader'],}, {test: /\.less$/,
use: ['style-loader'.'css-loader'.'less-loader'],}, {test: /\.scss$/,
use: ['style-loader'.'css-loader'.'sass-loader'],}, {test: /\.(png|gif|bmp|jpg)$/,
use: {
loader: 'url-loader'.options: {
limit: 8 * 1024.// The image takes a 10-bit hash and file extension
name: '[hash:10].[ext]'.// Disable es6 modularization
esModule: false.// Output path of image resource
outputPath: 'images',}}},// Process img resources in HTML
{
test: /.\html$/,
loader: "html-loader"
},
// Handle other resources
/ / {
// exclude: /\.(html|js|css|less|scss|jpg|png|gif)/,
// loader: "file-loader",
// outputPath:'media'
// },
{
test: /\.(woff(2)? |eot|ttf|otf|svg|)$/,
type: 'asset/inline'}, {test: /\.js/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'.options: {
presets: ['@babel/preset-env'].plugins: ['@babel/plugin-proposal-class-properties'],},},},],},// This parameter is configured when webpkk-dev-server is used
devServer: {
historyApiFallback: true.contentBase: path.join(__dirname, './dist'),
open: true.hot: true.quiet: true.port: 3000,}};Copy the code
Configure plug-ins in webpack.config.js
const { resolve } = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
// Import plugins that delete folders each time
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
// Reuse loader
const commonCssLoader = [
MiniCssExtractPlugin.loader,
'css-loader'.// CSS compatibility processing
// You also need to define browserList in package.json
'postcss-loader'
// Find the configuration file by path
/ / {
// loader: 'postcss-loader',
// options: {
// postcssOptions:{
// config:'./postcss.config.js'
/ /}
/ /}
// }
];
// Define node.js to the environment variable to determine which environment to use browserslist
process.env.NODE_ENV = 'production';
module.exports = {
entry: './src/main.js'.output: {
filename: 'js/bundle.js'.path: resolve(__dirname, 'dist')},module: {
rules: [{test: /\.css$/,
use: [
...commonCssLoader,
]
},
{
test: /\.less$/,
use: [
...commonCssLoader,
'less-loader']},/ / {
// // esLint syntax check, eslintConfig --> Airbnb validation rule in package.json
// test: /\.js$/,
// exclude: /node_modules/,
// // run first, run first esLint runs Babel
// enforce: 'pre',
// loader: 'eslint-loader',
// options: {
// fix: true
/ /}
// },
{
// js code compatibility handling
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'.options: {
presets: [['@babel/preset-env'.// Base presets
{
useBuiltIns: 'usage'.// Load as needed
corejs: {
version: 3
},
targets: {
// What version is compatible to the browser
chrome: '60'.firefox: '50'.ie: '9'.safari: '10'.edge: '17'}}]],plugins: ['@babel/transform-runtime'.'@babel/plugin-proposal-class-properties'],}}, {test: /\.(png|gif|bmp|jpg)$/,
use: {
loader: 'url-loader'.options: {
limit: 8 * 1024.// The image takes a 10-bit hash and file extension
name: '[hash:10].[ext]'.// Disable es6 modularization
esModule: false.// Output path of image resource
outputPath: 'images'.// publicPath: This is the generated page to the image path reference, add publicPath.
publicPath: ".. /images"}}},// Process img resources in HTML
{
test: /.\html$/,
loader: 'html-loader'
},
// Process other files
{
exclude: /\.(js|css|less|html|jpg|png|gif)/,
loader: 'file-loader'.options: { outputPath: 'media',},},]},plugins: [
// The CSS code is extracted separately
new MiniCssExtractPlugin({
filename: 'css/bundle.css'
}),
// CSS code compression
new OptimizeCssAssetsWebpackPlugin(),
// HTML file compression
new HtmlWebpackPlugin({
template: './src/index.html'.minify: {
// Remove whitespace
collapseWhitespace: true.// Remove comments
removeComments: true}}),// new ESLintPlugin({
// exclude:'node_modules',
// fix:true
// }),
new CleanWebpackPlugin(),
]
,
mode: 'production'
};
Copy the code
Postcss. Config. Js configuration
module.exports = {
// You can specify any options from https://postcss.org/api/#processoptions here
// parser: 'sugarss',
plugins: [
// Plugins for PostCSS
// ["postcss-short", { prefix: "x" }],
"postcss-preset-env",]};Copy the code
. Eslintlrc. Js configuration
module.exports = {
root: true.env: {
commonjs: true.es6: true.browser: true.node: true
},
extends: [
"airbnb-base".// 'plugin:vue/essential',
// '@vue/standard'].parserOptions: {
ecmaVersion: 7.ecmaFeatures: {
jsx: true.experimentalObjectRestSpread: true,},parser: 'babel-eslint'.sourceType: "module"
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off'.'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'}}Copy the code
. Gitignore configuration
node_modules/*
package-lock.json
dist/*
.idea/*
Copy the code
Package. The json configuration
{
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"."serve": "webpack serve"."dev": "webpack --config webpack.config.js"."build": "webpack --config webpack.pub.config.js"
},
"browserslist": {
"development": [
"last 1 chrome version"."last 1 firefox version"."last 1 safari version"]."production": [
"0.2%" >."not dead"."not op_mini all"]}}Copy the code
Problems encountered
- Development environment, reconfiguration of hot deployment devServer, add part of hot deployment code in webpack.config.js, and then configure the corresponding Webpack in scripts in package.json file
- Configuration of the production environment in package.json
"build": "webpack --config webpack.pub.config.js"
- The web page cannot be displayed after image resources are packaged in the production environment. You need to add image resources to the package
publicPath: ".. /images"
This is a reference to the image path in the generated page, plus publicPath, so that when accessing the file I can put the correct address. - Use postCSS-loader to load the postCSs-loader configuration file directly in use. You can also use the postcss-loader directly to load the postCSS configuration by automatically looking for the postcss.confgi.js configuration file in the root directory. This project uses the external postcss.confgi.js configuration file. Note: You also need to define browserList in package.json
- In addition: there are still lazy loading and esLint verification code functionality unfinished in the production environment, esLint verification issues
class Person { static info = { name: 'zs' }; }
Parsing error: new eslint-webpack-plugin () Parsing error: Parsing error: eslint-webpack-plugin () Parsing error: eslint-webpack-plugin () Parsing error: eslint-webpack-plugin () Parsing error: eslint-webpack-plugin () Parsing error: Unexpected token =
Gitee warehouse address
Gitee.com/heyhaiyon/w…