The use of WebPack relies on NodeJS, and the node version used in this article and beyond is 10.17.0.

Initialize the Node project

To start, switch to the project path and initialize a Node project in your local directory, which in this case is the webpack-study directory. The command for initialization is as follows:

cd webpack-study
npm init
Copy the code

Set the project name and other basic information according to the steps, and press Enter for other steps according to the default Settings. Once created, the basic package.json file is generated in the webpack-study directory.

Create code directory

Create a SRC directory under the webpack-study directory to hold the source code. Create index.js under SRC as an entry file. Here is a simple example:

const add = (x, y) = > x + y
console.log(add(1.2))
Copy the code

Install Webpack

npm i webpack webpack-cli
Copy the code

In addition to using Webpack, we will also use Webpack-CLI, which is the scaffolding for Webpack.

Create the Webpack configuration file

To use WebPack to package resources, first we need to configure the WebPack configuration file. We create the webpack.config.js file in the project root directory. In the last article, we mentioned the five basic concepts of Webpack. (For those who are not impressed, please check back: WebPack Learning Note 1: Some basics.) Now let’s create a simple WebPack configuration file based on the five basic concepts mentioned in the previous section:

// Introduce node's path module
const { resolve } = require('path')

module.exports = {
    // Import file
    entry: './src/index.js'.// File output configuration
    output: {
    	// The output file name
        // set [name] to the name of the entry file
    	filename: 'js/[name].js'.// The path to the output file
        // The output is in the build directory of the root directory. If you are not familiar with __dirname, you can check out nodejs
        path: resolve(__dirname, 'build')},// Used to configure loader
    module: {},
    // Used to configure plug-in information
    plugins: [].// Enable development mode
    mode: 'development'
}
Copy the code

Add a package command

The webpack command is webpack, and we can add some Settings to the command script:

// Development environment
webpack ./src/index.js -o ./build/index.js --mode=development
// Production environment
webpack ./src/index.js -o ./build/index.js --mode=production
Copy the code

Webpack uses development/production mode to package./ SRC /index.js with output (-O) to./build/index.js. As you might have noticed, the only difference between the two directives is that the mode parameter is development, which stands for development environment. The other one is production. So what’s the difference? We first configure the two instructions into the scripts of package.json so that we can execute them directly using NPM or YARN commands later. Of course, you can copy these two instructions directly to the console to run, but obviously this is not very convenient.

{
  "name": "webpack_study"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
    "build:dev": "webpack ./src/index -o ./build/index.js --mode=development"."build:prd": "webpack ./src/index -o ./build/index.js --mode=production"
  },
  "author": ""."license": "ISC"."dependencies": {
    "webpack": "4.41.6"."webpack-cli": "3.3.11."}}Copy the code

Then we’ll see the difference by executing build:dev and build: PRD, respectively.

In the webpack.config.js file, mode is configured: ‘development’, and in our package.json directive we specify –mode=’development’, so which one should prevail? The answer is the one configured in package.json. Interested partners can go to try ~

build:dev

npm run build:dev
Copy the code

After running this command, we can see the generated index.js file in the build/js path of the root directory. Open this file:

/ * * * * * * / (function(modules) { // webpackBootstrap
/ * * * * * * / 	// The module cache
/ * * * * * * / 	var installedModules = {};
/ * * * * * * /
/ * * * * * * / 	// The require function
/ * * * * * * / 	function __webpack_require__(moduleId) {
/ * * * * * * /
/ * * * * * * / 		// Check if module is in cache
/ * * * * * * / 		if(installedModules[moduleId]) {
/ * * * * * * / 			return installedModules[moduleId].exports;
/ * * * * * * / 		}
/ * * * * * * / 		// Create a new module (and put it into the cache)
/ * * * * * * / 		var module = installedModules[moduleId] = {
/ * * * * * * / 			i: moduleId,
/ * * * * * * / 			l: false./ * * * * * * / 			exports: {}
/ * * * * * * / 		};
/ * * * * * * /
/ * * * * * * / 		// Execute the module function
/ * * * * * * / 		modules[moduleId].call(module.exports, module.module.exports, __webpack_require__);
/ * * * * * * /
/ * * * * * * / 		// Flag the module as loaded
/ * * * * * * / 		module.l = true;
/ * * * * * * /
/ * * * * * * / 		// Return the exports of the module
/ * * * * * * / 		return module.exports;
/ * * * * * * / 	}
/ * * * * * * /
/ * * * * * * /
/ * * * * * * / 	// expose the modules object (__webpack_modules__)
/ * * * * * * / 	__webpack_require__.m = modules;
/ * * * * * * /
/ * * * * * * / 	// expose the module cache
/ * * * * * * / 	__webpack_require__.c = installedModules;
/ * * * * * * /
/ * * * * * * / 	// define getter function for harmony exports
/ * * * * * * / 	__webpack_require__.d = function(exports, name, getter) {
/ * * * * * * / 		if(! __webpack_require__.o(exports, name)) {
/ * * * * * * / 			Object.defineProperty(exports, name, { enumerable: true.get: getter });
/ * * * * * * / 		}
/ * * * * * * / 	};
/ * * * * * * /
/ * * * * * * / 	// define __esModule on exports
/ * * * * * * / 	__webpack_require__.r = function(exports) {
/ * * * * * * / 		if(typeof Symbol! = ='undefined' && Symbol.toStringTag) {
/ * * * * * * / 			Object.defineProperty(exports.Symbol.toStringTag, { value: 'Module' });
/ * * * * * * / 		}
/ * * * * * * / 		Object.defineProperty(exports.'__esModule', { value: true });
/ * * * * * * / 	};
/ * * * * * * /
/ * * * * * * / 	// create a fake namespace object
/ * * * * * * / 	// mode & 1: value is a module id, require it
/ * * * * * * / 	// mode & 2: merge all properties of value into the ns
/ * * * * * * / 	// mode & 4: return value when already ns object
/ * * * * * * / 	// mode & 8|1: behave like require
/ * * * * * * / 	__webpack_require__.t = function(value, mode) {
/ * * * * * * / 		if(mode & 1) value = __webpack_require__(value);
/ * * * * * * / 		if(mode & 8) return value;
/ * * * * * * / 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/ * * * * * * / 		var ns = Object.create(null);
/ * * * * * * / 		__webpack_require__.r(ns);
/ * * * * * * / 		Object.defineProperty(ns, 'default', { enumerable: true.value: value });
/ * * * * * * / 		if(mode & 2 && typeofvalue ! ='string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/ * * * * * * / 		return ns;
/ * * * * * * / 	};
/ * * * * * * /
/ * * * * * * / 	// getDefaultExport function for compatibility with non-harmony modules
/ * * * * * * / 	__webpack_require__.n = function(module) {
/ * * * * * * / 		var getter = module && module.__esModule ?
/ * * * * * * / 			function getDefault() { return module['default']; } :
/ * * * * * * / 			function getModuleExports() { return module; };
/ * * * * * * / 		__webpack_require__.d(getter, 'a', getter);
/ * * * * * * / 		return getter;
/ * * * * * * / 	};
/ * * * * * * /
/ * * * * * * / 	// Object.prototype.hasOwnProperty.call
/ * * * * * * / 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/ * * * * * * /
/ * * * * * * / 	// __webpack_public_path__
/ * * * * * * / 	__webpack_require__.p = "";
/ * * * * * * /
/ * * * * * * /
/ * * * * * * / 	// Load entry module and return exports
/ * * * * * * / 	return __webpack_require__(__webpack_require__.s = "./src/js/index.js");
/ * * * * * * / })
/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /
/ * * * * * * / ({

/ * * * / "./src/js/index.js":
/ *! * * * * * * * * * * * * * * * * * * * * * * * * *! * \! *** ./src/js/index.js ***! A \ * * * * * * * * * * * * * * * * * * * * * * * * * /
/ *! no static exports found */
/ * * * / (function(module.exports) {

eval("const add = (x, y) => x + y; \n\nconsole.log(add(1, 2)); \n\n\n//# sourceURL=webpack:///./src/js/index.js?");

/ * * * / })

/ * * * * * * / });
Copy the code

Sliding to the bottom, we can see that the previously written code was converted into a string and written into the EavL method with the source path as the key, value as well as an object as an input parameter and passed into the packaged generated method.

build:prd

Let’s take a look at what the generated file looks like by running the Build: PRD package:

npm run build:prd
Copy the code

After completion, the following code is generated:

!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1.exports: {}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0.get:r})},n.r=function(e){"undefined"! =typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule", {value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"= =typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default", {enumerable:!0.value:e}),2&t&&"string"! =typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=0)} ([function(e,t){console.log(1+2)}]);
Copy the code

We noticed that the code was much leaner. There were no comments, no white space folds, obviously the code had been compressed. It can be concluded that:

Compared to the Development mode, the Production mode compresses the packaged code. This is mainly because the UglifyJsPlugin plug-in of WebPack is enabled in Production mode, which is used to compress the code.

Console output

Once the packaging is complete, let’s go back and take a quick look at the information displayed in the console. Let’s take a look at the console output after packaging:

Let’s take a look at what these parameters mean in turn:

Hash: unique ID generated after packaging. It can be used as a unique representation in the file name to prevent cache access. Version: Indicates the webpack Version. Time: Time spent packing; Built at: the time when packing started; Asset: a packaged resource; Size: indicates the file Size. “Chunks” : the name of the chunk to which they belong. Chunk Names: Names of chunks. EntryPoint main: entry file name; […]. : the module that participates in the packaging, which is the static module mentioned in the previous section.

At this point, we have implemented a simple WebPack packaging function, and some basic WebPack configuration, packaging commands and different modes of packaging in a simple understanding. At the same time, we know the meaning of the output from the console. In the following chapters, I will introduce the other functions of WebPack in order to help you gradually become familiar with webPack configuration, so that you will not be confused with webPack configuration in the later development process. The length may not be too long, but I hope it will be helpful to my friends