The preparatory work

Before joining the build for the project, you need to create a new Web project, as follows:

  • Create a new directory, go to the project root directory and execute NPM init
  • Use the scaffolding tool Yeoman(Yeoman.io) to directly and quickly generate a project that best meets your needs

Install webpack into this project

Install Webpack to this project, you can choose any command to run according to your own needs

# NPM I -d is short for NPM install –save-dev and refers to devDependencies that install the module and save to package.json

Install the latest stable version of NPM I-D WebPack

Install the latest experience version NPM i-d webpack@beta

Install WebPack globally

npm i -g webpack

This installation is recommended to prevent conflicts between projects that rely on different versions of Webpack

A simple practical

  1. NPM install webpack –save–dev(yarn add webpack is recommended)
  2. NPM init(create a package.json file, this time using YARN init)
  3. Json file **”scripts”: {“start”: “webpack –config webpack.config.js”

},** 4. Build the project directory as follows

Project directory

  • index.html
  • main.js
  • show.js
  • webpack.config.js
index.html
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta HTTP-equiv =" x-UA-compatible "content=" IE =edge"> <title>Document</title> </head> <body> <div id="app"> </div> </body> <script src="./dist/bundle.js"></script> </html>Copy the code
main.js
// Import show function from commonJS const show = require('./show.js'); show('Webpack');Copy the code
show.js
// Manipulate the DOM element, Will display the content to the page on the function show (content) {window. The document. The getElementById (' app '.) innerHTML (" hello "+ content)} module. Exports  = show;Copy the code
webpack.config.js
const path = require('path'); Module.exports = {// JavaScript executes the entry file entry: './main.js', output:{// consolidates all dependent modules into a bundle.js file filename: Resolve (__dirname, './dist'),}}Copy the code
Start to perform
npm run start
Copy the code

Finally, a dist directory is generated under the directory, and a bundle.js file is generated under the directory. Bundle. js is an executable javascript file, which contains the two modules main.js and show.js on which the page depends. And the built-in webpackBootstrap startup function. Open the index.html page in your browser and you’ll see Hello Webpack

conclusion

This chapter is just a brief introduction to the simple use of Webpack, through this chapter should remember how to build a WebPack environment. In the next chapter, I will explain how to use Loader, Plugin, and DevServer

Author: Feng Tengfei, Freely Big front end RESEARCH and development Center