preface

Recently, I found that most programmers’ understanding of WebPack is based on the configuration set up by various frameworks, without in-depth understanding, including myself, so I decided to share my own learning process of WebPack configuration. The first chapter introduces:

  • The installation of the webpack
  • Webpack dev – the use of server
  • Compile CSS, SCSS files
  • Compiling JS files
  • Compile images, font files

Install webpack

/ / installation
npm install webpack webpack-cli -D
// Create the configuration file webpack.config.js in the project root directory
// You can also customize the configuration file name, such as webpack.dev.js for development environment and webpack.prod.js for production environment

// Execute the package command
webpack  // This is using the default configuration file
webpack --config webpack.prod.js // This is using a custom configuration file

// the webpack command is generally configured in the scripts parameter of package.json file
{
  "name": "css"."version": "1.0.0"."scripts": {
    "build": "webpack"."build": "webpack --config webpack.prod.js"."watch": "webpack --watch",}}Copy the code

Monitor for file changes and automatically update compiled files

// The first method, using watch, has the disadvantage of manually refreshing the browser
// package.json
{
  "name": "css"."version": "1.0.0"."scripts": {
    "watch": "webpack --watch"}}// The second method uses webpack-dev-server
npm install webpack-dev-server -D
// package.json
{
  "name": "css"."version": "1.0.0"."scripts": {
    "dev": "webpack-dev-server --config webpack.dev.js --open"}}// Config file webpack.dev.js
const webpack = require('webpack')
const path = require('path')
module.exports = {
  plugins: [
    new webpack.HotModuleReplacementPlugin() // Hotreplace plugin].devServer: {
    host: "0.0.0.0".// Can be accessed using a local IP address
    hot: true.// Enable webPack's module hot replace feature
    open: true.// Automatically open the browser
    contentBase: path.join(__dirname, "dist"), // Tell the server where to supply the content. Only if you want to provide static files. Multiple paths can be configured using arrays
    proxy: { // Configure cross-domain
      "/api": {
        target: "http://localhost:3000".pathRewrite: {"^/api" : ""}}}}};Copy the code

Parse SCSS files and CSS files

  • The compiled CSS is inserted into the page head using the style tag
// install style-loader css-loader sass-loader node-sass

npm install style-loader css-loader sass-loader node-sass -D
npm install html-webpack-plugin -D
// webpack.config.js

// use the @type annotation below to have vscode automatically prompt you for webpack parameters
/ * *@type {import('webpack').Configuration} * /
// Generate HTML from the template HTML
const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require('path')
module.exports = {
  entry: "./src/main.js".// Import file
  mode: "development".// Development mode
  output: {
    path: path.join(__dirname, 'dist'), // Output path
    filename: "app.js",},module: {
    rules: [{test: /\.scss$/,
        use: ["style-loader"."css-loader"."sass-loader"],}, {test: /\.css$/,
        use: ["style-loader"."css-loader"],},],},plugins: [
    new HtmlWebpackPlugin({
      template: path.join(__dirname, "index.html"),
      filename: "index.html"})]};Copy the code
  • Separate out the CSS file and import it into the page using link
// Install csS-loader sass-loader node-sass to compile SCSS files
npm install css-loader sass-loader node-sass -D
npm install html-webpack-plugin -D
npm install mini-css-extract-plugin -D
npm install optimize-css-assets-webpack-plugin -D

// webpack.config.js

// Extract CSS as a separate CSS file
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// Reduce the CSS volume
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin')
// Generate HTML from the template HTML
const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require('path')
module.exports = {
  entry: "./src/main.js".mode: "development".output: {
    path: path.join(__dirname, 'dist'),
    filename: "app.js",},module: {
    rules: [{test: /\.scss$/,
        use: [
          // "style-loader", 
          MiniCssExtractPlugin.loader,
          "css-loader"."sass-loader"],}, {test: /\.css$/,
        use: [
          // "style-loader", 
          MiniCssExtractPlugin.loader,
          "css-loader"],},],},plugins: [
    new MiniCssExtractPlugin({
      filename: 'index.css'
    }),
    new OptimizeCssAssetsPlugin({
      assetNameRegExp: /\.css$/g,
      cssProcessor: require('cssnano') // The CSS processor used to optimize/minimize CSS
    }),
    new HtmlWebpackPlugin({
      template: path.join(__dirname, "index.html"),
      filename: "index.html"})]};Copy the code

Parsing a JS file

// Install Babel
npm install babel-loader @babel/core @babel/preset-env -D
// create the.babelrc file
{
  "presets": [
      "@babel/preset-env"]}// webpack.config.js
const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require('path')

module.exports = {
	entry: './src/main.js'.mode: 'development'.output: {
		path: path.join(__dirname, 'dist'),
		filename:'app.js'
	},
	module: {
		rules: [{// File suffix
				test: /\.js$/,
				use: "babel-loader".// A file that does not need to be compiled
				exclude:/(node_modules)/}},devtool: 'source-map'.// Generate a map file to locate errors directly
	plugins: [new HtmlWebpackPlugin({
			template: path.join(__dirname, 'index.html'),
			filename: 'index.html'.inject: true.// Put the packed js file at the end of the body
			minify: false / / no compression}})]Copy the code

Parse image font files

// Parse image files in JS and font files in CSS
npm install file-loader -D
// Parse images and video files in HTML
npm install html-withimg-loader -D

// webpack.config.js

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
/ * *@type {import('webpack').Configuration} * /
module.exports = {
  entry: './src/index.js'.output: {
    path: path.join(__dirname, 'dist'),
    filename: 'index.js'
  },
  mode: 'development'.module: {
    rules: [{test: /.(png|jpg|gif|jpeg)$/,
        use:{
          loader: 'file-loader'.options: {outputPath: 'img/'.// Image output folder
            esModule: false // with the html-withimg-loader plugin}}}, {test: /.(woff|woff2|eot|ttf|otf|TTF)$/,
        use: 'file-loader'
      },
      {
        test: /.css$/,
        use: ['style-loader'.'css-loader'] {},test: /.js$/,
        use: 'babel-loader'
      },
      {
        test: /.(htm|html)$/,
        use: 'html-withimg-loader' // Allow images referenced in HTML to be compiled to}},plugins: [
    new HtmlWebpackPlugin({
      template: path.join(__dirname, 'index.html'),
      filename: 'index.html'.inject: true.minify: false}})]Copy the code