Webpack is now an indispensable tool for developing Single Page applications.

WebPack can be thought of as a module processor, as shown above. What it does is, it takes some input, it processes some output.

The inputs are module files for our Web front-end project, and typically these files cannot be executed directly by the browser’s JavaScript execution engine.

The output is webpack processed javascript and static resource files that can be used by browsers. ES6 js to ES5 JS, CSS preprocessor files to CSS files, etc.

Let’s do a concrete example. This example takes only 10 minutes to familiarize us with the basic usage of WebPack.

1. Create a package.json file with the NPM init command:

Use the command line NPM install –save-dev webpack below to install webpack and save it under devDependencies in the project’s package.json.

It took a minute to execute.

After executing, check package.json and see that WebPack appears in the devDependencies section.

At this point, the project folder hierarchy is shown as follows:

2. Create an index. HTML file and enter the following content:

<html>

<div id="app"></div>

<script src="./dist/bundle.js"></script>

</html>
Copy the code

As you can see from the source code, this HTML references an output file generated when WebPack is packaged.

Since it is modular development, we will create a new module and put the implementation file in print.js:

function print(content){

    window.document.getElementById("app").innerText = "Hello," + content;

}

module.exports = print;
Copy the code

This module implements a print function that displays the string passed in to the div tag with the id app in index.html.

Now that we have the Module, we also need to execute it. To do this, create a new main.js file and enter the following:

const print = require("./print.js");

print("Jerry");
Copy the code

Finally, we need to generate the bundle.js file used by index.html. To do this, we define a task for Webpack, which is done by creating a new file, webpack.config.js.

The entry field defines the input to Webpack: main.js, and the output is placed in bundle.js under the current directory dist.

const path = require("path");

module.exports = {

entry: "./main.js".output: {

filename: "bundle.js".path: path.resolve(__dirname, "./dist"),},mode: 'development' / / set mode

};
Copy the code

At this point, the material in the webpack_demo folder looks like this:

Execute command line webpack:

After executing webpack, open index.html and see what we expect from Hello Jerry:

At this point, one of the simplest WebPack examples has run its course.

For more of Jerry’s original articles, please follow the public account “Wang Zixi “: