1. What is Webpack?

Essentially, Webpack is a static module packaging tool.

2. Why Webpack?

In development, we often encounter:

  • Writing styles using sass and less syntax require translation
  • Use es6 and later syntax to simplify code that browsers cannot recognize
  • Large project volume is not conducive to online

Webpack solves these problems:

  • Supports packaging of all types of files
  • If less or SASS is supported, go to the CSS
  • If es6/7/8 is supported, go to ES5
  • Compress code for faster loading

Thus, WebPack is a necessity in the front-end developer’s technical library!

3. Use of Webpack

Install the Node environment before using node.js (nodejs.org/).

3.1. Download the YARN Package manager

Chinese official website address: yarn.bootcss.com/

Download address: yarn.bootcss.com/docs/instal…

 npm i -g yarn 
Copy the code

3.2 Installation of Webpack

  1. Create a project folder
  2. Initialize the package environment in the project folder
yarn init -y 
Copy the code
  1. Install the WebPack dependencies
yarn add webpack webpack-cli -D
Copy the code
  1. In package.json, configure scripts to customize the packaging command
scripts: {
	"build": "webpack"
}
Copy the code

3.3. Simple use of Webpack

  1. Create a new SRC /js.js and write and export the code that needs to be packaged, for example:
export const add = (a, b) => a + b
Copy the code
  1. Create a SRC /index.js import to use
Import {add} from './js' console.log(add(2, 3));Copy the code
  1. Run custom packaging commands
yarn build
Copy the code

Effect of 3.4,

Generate the dist directory (the same as the SRC folder) and its main.js file

(()=>{"use strict"; console.log(5)})();Copy the code

4. Webpack packaging process

  • Execute the local webpack command (webpack was downloaded in the prerequisite project)
  • There is webpack.config.js for reading, otherwise use built-in defaults
  • Establish import relationships based on the entry
  • Compilation and translation integrate packaged output to the specified location

Note: module files can only be packaged if they have a direct or indirect import relationship with the Webpack entry!