1. Create a project

Install NodeJS and create the project using NPM

Mkdir projectname //projectname is the name of the project, here we first use the mkdir command to create the project directory CD projectname // enter the directory NPM init -y // create the projectCopy the code

Of course, you can create a directory directly on the disk with the mouse, and then switch to the DOS command window to create the project. When the project is created, the package.json file is generated in the directory

2. Install webPack and webpack-CLI

It is recommended to use YARN to install project dependency packages. First, run the following command to install the YARN tool:

npm install -g yarn
Copy the code

Install the WebPack tool and the Webpack-CLI command line package:

yarn add webpack webpack-cli --dev
Copy the code

With the –dev argument, you specify to install the dependencies into devDependencies

Dependencies vs. devDependencies

  • DevDependencies is used in local environment development.

  • Dependencies The user publishing environment

DevDependencies are modules that will only be relied on in the development environment, not in the production environment. Specify the development or production environment with NODE_ENV=developement or NODE_ENV=production. Dependencies include packages that are available to your production environment as well as your development environment.

3. Configure the entry file

Create a new SRC directory in the directory and create the entry file index.js

//index.js
alert('hellow');
Copy the code

Modify the package.json file and specify the entry file as SRC /index.js, as follows:

{
  "name": "frontend"."version": "1.0.0"."description": ""."main": "src/index.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": []."author": ""."license": "ISC"."dependencies": {},"devDependencies": {
    "webpack": "^ 5.40.0"."webpack-cli": "^ 4.7.2." "}}Copy the code

4. Configuration webpack

Create the webpack.config.js configuration file in the project directory as follows:

module.exports = {
    mode:"development"
}
Copy the code

5. Run webPack to compile the build project

webpack
Copy the code

After executing the above command, the dist directory is generated in the root directory and a packaged main.js file is generated. We create a new index. HTML file in the SRC directory and introduce main.js in the dist directory. Run this file and see the hellow pop up.

6. The configuration scripts

To implement custom packaging instructions by configuring scripts, we configure WebPack in the package.json scripts:

{
  "name": "frontend"."version": "1.0.0"."description": ""."main": "src/index.js"."scripts": {
    "dev":"webpack"."test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": []."author": ""."license": "ISC"."dependencies": {
    "jquery": "^ 3.6.0"
  },
  "devDependencies": {
    "webpack": "^ 5.40.0"."webpack-cli": "^ 4.7.2." "}}Copy the code

Then we can run the WebPack build project using yarn dev or NPM dev.

7. Configure the webPack entry and output files

In Webpack 4.x, SRC /index.js is the default package entry js file and dist/main.js is the default package output JS file. This can be changed by configuring webpack.config.js

const path = require("path");  // Import modules in Node.js that operate on paths
module.exports = {
    mode:"development".entry: path.join(__dirname,"./src/index.js"),// Set the entry file path
    output: {// Set the output file path
       path:path.join(__dirname,"./dist"),
       // Set the output file name
       filename:"bundle.js"}}Copy the code

8. Install the third-party package

  • Install the jquery

    Yarn add jquery@last // Here we select version 1.12.4Copy the code
  • Install the bootstrap

    Yarn add bootstrap@last // Here we select version 3.4.1Copy the code

Create a js directory in the SRC directory to put our script files, and an app.js file in the JS directory to use jquery and bootstrap

$(function(){$("li:odd").css("background"."cyan");
    $("li:odd").css("background"."pink");
});
Copy the code

Bootstrap jquery/bootstrap jquery/bootstrap

window$=window.jQuery = require('jquery');
require('bootstrap');
require('./js/app.js'); / / introduction of the app. Js
Copy the code

Run yarn dev to build the project

9. Configure the local hot start server

  • Install the Webpack-dev-server plug-in to automatically pack and start the local server
yarn add webpack-dev-server --dev
Copy the code

Modify the dev directive in package.json scripts to look like this:

{
  "name": "frontend"."version": "1.0.0"."description": ""."main": "src/index.js"."scripts": {
    "dev": "webpack-dev-server"."test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": []."author": ""."license": "ISC"."dependencies": {
    "bootstrap": "^ 3.4.1 track"."jquery": "^ 1.12.4"
  },
  "devDependencies": {
    "webpack": "^ 5.40.0"."webpack-cli": "^ 4.7.2." "}}Copy the code

Change the script reference path in SRC /index.html to “/ bulds.js”

  • Configure the default preview page and install the HTml-Webpack-plugin
Yarn add html-webpack-plugin@last --dev // Install the 4.x version. The 3.x version is incompatible with webpack-cli4.xCopy the code

Using the html-webpack-plugin, you can generate a preview page and modify the webpack.config.js file as follows:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    mode:"development".entry: path.join(__dirname,"./src/index.js"),// Set the entry file path
    output: {// Set the output file path
       path:path.join(__dirname,"./dist"),
       // Set the output file name
       filename:"bundle.js"
    },
    devServer: {
        // Local server proxy
        compress: true.port: 8080.// Configure the port
        hot: true.// Configure hot update
    },
    plugins: [new HtmlWebpackPlugin({
            // Set the template file to generate the preview page
            template:"./src/index.html".// Set the name of the generated preview page. This file exists in memory and does not show in the directory
            filename:"index.html"}})]Copy the code

Run yarn dev, access http://localhost:8080 in the browser, and view the automatic packaging effect

Configure the WebPack loader

By default, webPack can only package JS files, other files need to install the corresponding loader to be packaged, such as CSS \less\sass, etc., front-end project source code is generally not directly use CSS, basically using sass or less coding and then packaged into CSS through the loader

  • Package CSS files

You need to install csS-Loader and style-Loader to process the CSS

yarn add css-loader --dev
Copy the code

Configuration webpack. Config. Js

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    mode:"development".entry: path.join(__dirname,"./src/index.js"),// Set the entry file path
    output: {// Set the output file path
       path:path.join(__dirname,"./dist"),
       // Set the output file name
       filename:"bundle.js"
    },
    plugins: [new HtmlWebpackPlugin({
            // Set the template file to generate the preview page
            template:"./src/index.html".// Set the name of the generated preview page. This file exists in memory and does not show in the directory
            filename:"index.html"})].module: {
		rules: [{//test Sets the file type to be matched. Re is supported
                test: /\.css$/.// Use indicates the loader to be called for the file type
                use: ['css-loader'[}]}Copy the code
  • Packaging less

To handle less, you need to install less and less-loader

yarn add less-loader less --dev
Copy the code

Modify webpack.config.js as follows

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    mode:"development".entry: path.join(__dirname,"./src/index.js"),// Set the entry file path
    output: {// Set the output file path
       path:path.join(__dirname,"./dist"),
       // Set the output file name
       filename:"bundle.js"
    },
    plugins: [new HtmlWebpackPlugin({
            // Set the template file to generate the preview page
            template:"./src/index.html".// Set the name of the generated preview page. This file exists in memory and does not show in the directory
            filename:"index.html"})].module: {
		rules: [{test: /\.css$/,use: ['css-loader']},// Configure the CSS loader
			{ test: /\.less$/,use: ['css-loader'.'less-loader']}// Configure the less loader]}}Copy the code
  • Package images and fonts

Webpack5 allows applications to use resource files (images, fonts, etc.) without configuring additional loaders or installing URl-Loaders and file-loaders

yarn add url-loader file-loader --dev
Copy the code

Modify webpack.config.js as follows

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    mode:"development".entry: path.join(__dirname,"./src/index.js"),// Set the entry file path
    output: {// Set the output file path
       path:path.join(__dirname,"./dist"),
       // Set the output file name
       filename:"bundle.js"
    },
    plugins: [new HtmlWebpackPlugin({
            // Set the template file to generate the preview page
            template:"./src/index.html".// Set the name of the generated preview page. This file exists in memory and does not show in the directory
            filename:"index.html"})].module: {
		rules: [{test: /\.css$/,use: ['css-loader']},// Configure the CSS loader
			{ test: /\.less$/,use: ['css-loader'.'less-loader']},// Configure the less loader
			{
          test: /\.ttf|eot|svg|woff|woff2$/,
          type: "asset/resource".generator: {
              // Output the file location and file name
              filename: "fonts/[name][ext]"}}, {test: /\.jpg|png|gif|bmp$/,
          type: "asset/resource".generator: {
              // Output the file location and file name
              filename: "images/[name][ext]"
          },
          parser: {
              dataUrlCondition: {
                  maxSize: 10 * 1024 // Base64 is not converted when the size exceeds 10KB}}},]}}Copy the code
  • Package advanced JS files

If your project uses advanced JS syntax such as Es6, you need to use the Babel family of extension packs for compilation processing

1. Install the Babel converter

yarn add babel-loader @babel/core @babel/runtime --dev
Copy the code

2. Install the Babel syntax plug-in package

yarn add @babel/preset-env @babel/plugin-transform-runtime @babel/plugin-proposal-class-properties --dev
Copy the code

Create and configure the babel.config.js file in the project root directory

module.exports = {
	presets: ["@babel/preset-env"].plugins: ["@babel/plugin-transform-runtime"."@babel/plugin-proposal-class-properties"]}Copy the code

Configure webpack.config.js to support Babel conversions

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    mode:"development".entry: path.join(__dirname,"./src/index.js"),// Set the entry file path
    output: {// Set the output file path
       path:path.join(__dirname,"./dist"),
       // Set the output file name
       filename:"bundle.js"
    },
    plugins: [new HtmlWebpackPlugin({
            // Set the template file to generate the preview page
            template:"./src/index.html".// Set the name of the generated preview page. This file exists in memory and does not show in the directory
            filename:"index.html"})].module: {
		rules: [{test: /\.css$/,use: ['css-loader']},// Configure the CSS loader
			{ test: /\.less$/,use: ['css-loader'.'less-loader']},// Configure the less loader
			{
          test: /\.ttf|eot|svg|woff|woff2$/,
          type: "asset/resource".generator: {
              // Output the file location and file name
              filename: "fonts/[name][ext]"}}, {test: /\.jpg|png|gif|bmp$/,
          type: "asset/resource".generator: {
              // Output the file location and file name
              filename: "images/[name][ext]"
          },
          parser: {
              dataUrlCondition: {
                  maxSize: 10 * 1024 // Base64 is not converted when the size exceeds 10KB}}}, {test: /\.js$/, use: 'babel-loader'.exclude: /node_modules/}}}]Copy the code

11. Extract THE CSS file and set the font image output directory

After the above configuration, did you find that our CSS file is not extracted into a separate file, so we need to use the MiniCssExtractPlugin to extract the CSS and save it as a separate file

yarn add mini-css-extract-plugin --dev
Copy the code

Configuration webpack. Config. Js

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
    mode:"development".entry: path.join(__dirname,"./src/index.js"),// Set the entry file path
    output: {// Set the output file path
       path:path.join(__dirname,"./dist"),
       // Set the output file name
       filename:"bundle.js"
    },
    plugins: [// Extract the CSS as a separate file and generate it into dist/ CSS directory
        new MiniCssExtractPlugin({filename: "./css/[name].css"}),
        new HtmlWebpackPlugin({
            // Set the template file to generate the preview page
            template:"./src/index.html".// Set the name of the generated preview page. This file exists in memory and does not show in the directory
            filename:"index.html"})].module: {
		rules: [{test: /\.css$/,use: [MiniCssExtractPlugin.loader,'css-loader'] {},test: /\.less$/,use: [MiniCssExtractPlugin.loader,'css-loader'.'less-loader'] {},test: /\.ttf|eot|svg|woff|woff2$/,
          type: "asset/resource".generator: {
              // Output the file location and file name
              filename: "fonts/[name][ext]"}}, {test: /\.jpg|png|gif|bmp$/,
          type: "asset/resource".generator: {
              // Output the file location and file name
              filename: "images/[name][ext]"
          },
          parser: {
              dataUrlCondition: {
                  maxSize: 10 * 1024 // Base64 is not converted when the size exceeds 10KB}}},]}}Copy the code

12. Clean up the dist directory

Many files are generated in the dist directory after each package generation. In order to avoid redundant files, we need to clean up the dist directory before generation, so we need to use the CleanWebpackPlugin plugin to automatically clean up during packaging:

yarn add clean-webpack-plugin --dev
Copy the code

Configuration webpack. Config. Js

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
    mode:"development".entry: path.join(__dirname,"./src/index.js"),// Set the entry file path
    output: {// Set the output file path
       path:path.join(__dirname,"./dist"),
       // Set the output file name
       filename:"js/[name].js"
    },
    plugins: [// Extract the CSS as a separate file and generate it into dist/ CSS directory
        new MiniCssExtractPlugin({filename: "./css/[name].css"}),
        new HtmlWebpackPlugin({
            // Set the template file to generate the preview page
            template:"./src/index.html".// Set the name of the generated preview page. This file exists in memory and does not show in the directory
            filename:"index.html"
        }),
        new CleanWebpackPlugin(),// Clean up the build].module: {
    rules: [{test: /\.css$/,use: [MiniCssExtractPlugin.loader,'css-loader'] {},test: /\.less$/,use: [MiniCssExtractPlugin.loader,'css-loader'.'less-loader'] {},test: /\.ttf|eot|svg|woff|woff2$/,
          type: "asset/resource".generator: {
              // Output the file location and file name
              filename: "fonts/[name][ext]"}}, {test: /\.jpg|png|gif|bmp$/,
          type: "asset/resource".generator: {
              // Output the file location and file name
              filename: "images/[name][ext]"
          },
          parser: {
              dataUrlCondition: {
                  maxSize: 10 * 1024 // Base64 is not converted when the size exceeds 10KB}}},]}}Copy the code

12. Configure multi-page projects

In our daily project development, a project is composed of multiple pages, so how do we configure WebPack to output different pages to generate separate JS and CSS files? Let’s proceed with the multi-page configuration.

  • Create a new page, SRC /about.html
  • Create a new script SRC /js/about.js
  • Create a new style SRC /less/about.less

Configure webpack.config.js to implement multiple entries

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
    mode:"development".entry: {
        'index': path.join(__dirname,"./src/index.js"),
        'about': path.join(__dirname,"./src/js/about.js")},// Set the entry file path
    output: {// Set the output file path
       path:path.join(__dirname,"./dist"),
       // Set the output file name
       filename:"js/[name].js"
    },
    devServer: {
        // Local server proxy
        compress: true.port: 8080.// Configure the port
        hot: true.// Configure hot update
    },
    plugins: [new MiniCssExtractPlugin({filename: "./css/[name].css"}),
        new HtmlWebpackPlugin({
            template:"./src/index.html".filename:"index.html"
        }),
        new HtmlWebpackPlugin({
            template:"./src/about.html".filename:"about.html"
        }),
        new CleanWebpackPlugin(),
    ],
    module: {
    rules: [{test: /\.css$/,use: [MiniCssExtractPlugin.loader,'css-loader'] {},test: /\.less$/,use: [MiniCssExtractPlugin.loader,'css-loader'.'less-loader'] {},test: /\.ttf|eot|svg|woff|woff2$/,
          type: "asset/resource".generator: {
              // Output the file location and file name
              filename: "fonts/[name][ext]"}}, {test: /\.jpg|png|gif|bmp$/,
          type: "asset/resource".generator: {
              // Output the file location and file name
              filename: "images/[name][ext]"
          },
          parser: {
              dataUrlCondition: {
                  maxSize: 10 * 1024 // Base64 is not converted when the size exceeds 10KB}}}, {test: /\.js$/, use: 'babel-loader'.exclude: /node_modules/}}}]Copy the code

12. Release the project

Configure package.json to add the publish command to scripts

"scripts":{
	"dev":"webpack-dev-server",
	"build":"npx webpack"
}
Copy the code

Run yarn build to package and publish the project