Front-end and mobile development - webpack --- webpack installation and basic use

webpack

Contrast traditional development and engineering

Take the development of the same function as an example to compare and show two development methods:

  • A. Traditional way, without using build tools
  • B. Engineering method, use webpack

Insert picture description here

Schematic comparison

Traditional way

Insert picture description here

All the resources are directly cited in the .html. It is simple and clear for you to write, but it is also convenient for others to copy.

Engineering

When developing, write on the source code;

When publishing, use the tool (webpack) to package into the target code (it has been encrypted here), and then come and introduce the .html

Insert picture description here

Detailed comparison

Traditional way Engineering method
Can we adopt js modularization (introducing another js in one js) Can't can
Can js code be encrypted Can't can
Can css code be compressed Can't can
Whether to support css precompiled language Can't can

summary

Webpack is a tool. After introducing this tool, you can change the development method (traditional development -> engineering development) to improve development efficiency;

Examples of traditional projects

Suppose there is a traditional development project, how to transform it in an engineering way.

Structure content

Create three files index.html, index.js, tool.js, the overall project structure is:

|-yourproject/
|---index.html
|---index.js
|---tool.js

Copy the following materials:

index.html

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>index</title>
  </head>
  <body>
    <div id="app">
      
    </div>
    <!-- 引入两个js文件 -->
    <script src="./tool.js"></script>
    <script src="./index.js"></script>
</body>
</html>

tool.js

// 封装一个工具函数
// 把给指定id的元素设置内容
const updateDom = (id, content) =>{
    
    
  document.getElementById(id).innerHTML =  content
}

index.js

updateDom('app','index.html')

Description:

  • Introduce multiple js files in one html, and pay attention to their order relationship.
  • The script code is at the bottom of the body, which ensures that the dom node is rendered before the js code is executed.

Icon

Because the function of tool.js is used in index.js, index.js and tool.js are also referenced in index.html, and the reference of tool.js is placed before the reference of index.js. The following schematic diagram of the entire code:

Insert picture description here

summary

The above code has the following problems:

  • There is a sequential reference relationship between js files: because tool.js is referenced in index.js, tool.js must be placed before index.js.
  • There is variable pollution : variables defined in one file may be modified or overwritten in another file.
  • As the number of .js files increases, the project will become less and less manageable.
  • The technology of modularization (introducing another js into one js) cannot be used for development.
    • import , export

Basic introduction to webpack

In the previous traditional project, we raised some problems and mentioned the introduction of a special tool: webpack to solve this problem.

webpack is a * 静态模块打包器(module bundler)* of a modern JavaScript application .

Insert picture description here

Its core idea is: everything is a module, and modules can be packaged.

Related to the webpack business, products with relevant competitiveness include:

But overall, in front-end development, webpack has an absolute advantage: the three front-end frameworks of vue, react, and angular all rely on webpack for packaging. (Using these three frameworks to develop projects is inseparable from webpack)

How to introduce and use webpack in the project

We talked about two points above: 1 Traditional projects have shortcomings; 2. Webpack can be used to solve these problems.

Next, let's learn how to use webpack in the project.

The basic steps

  1. Use npm to initialize the project and install webpack.(要先有项目,然后再用webpack来优化开发)
  2. Modify the directory structure to enjoy the benefits of zero configuration
  3. Modify the code slightly, rewrite the code in a modular way
  4. Use webpack to package the source file (js) and generate the target file
  5. Introduce the goal after packaging in the html file

Initialize the project

If it is an existing project, directlynpm init

node is an environment;

npm is a tool bundled with node to download npm packages

webapck is a tool based on the node environment. It must be run in the node environment. If node is not installed on your computer, webpack will not run.

If the project has not been created before, create an empty folder arbitrarily, for example, name it webpack-demo, enter the folder, and use the following command to generate a package.json

npm init -y 

Install webpack in the project

Considering that different webpack versions may be used in different projects, local (partial) installation is used here. Review the difference between local installation and global installation.

npm i XXXX -g  # 全局安装
npm i xxxx     # 本地安装 不加-g

Install webpack

npm i [email protected] [email protected] -D

-------------------------------------------
+ [email protected]
+ [email protected]
added 392 packages from 220 contributors in 33.984s

tip: If you do not additionally specify the version of the package to be installed, it will definitely install the latest one. On 2020.10.10, webpack came out to 5, because other plugins did not keep up in time, so it is relatively stable to use 4 now.

  • When installing a package, if -D is added, it means that the package is a development dependency, if not, it is a production dependency by default.

Development dependency: Assuming you are building a house now, you need to use an excavator. This excavator is a development dependency (after the house is completed, it is no longer necessary to cross the river to demolish the bridge).

Production dependence: Suppose you build a house now, you need to use wires and water pipes. This wire and water pipe are production dependent (after the house is completed, it will be used).

If you see the output shown above, it means the installation has been successful. At the same time, you can also observe under node_modules.

Check if the installation is successful

# 方式一:
node_modules\.bin\webpack -v
# 方式二:
npx webpack -v

note:

  • The name of the project cannot be takenwepback

  • Since webpack and not a global installed , it can not be used directly webpack -vto do the test.

  • npx is a new feature provided after npm5.2. It will node_modules/.bincheck whether the command exists in it when it is running .

Adjust code structure

This step is not necessary, just to enjoy the out of the box (webpack zero configuration) benefits.

Do one thing: put the three file codes in srca directory named

|-package.json
|-src
|--index.html
|--index.js
|--tool.js

After adjusting the directory structure, there is a file named index.js under src. In the subsequent operations, we can enjoy the benefits of zero configuration.

Since webpack supports the src directory by default, the directory name can only be src.

Modify code content

The following content will use the wording of export and import, which are the modular syntax of es6 and are used in conjunction.

Of course, you can also use module.exports and require in nodejs to model it.

To write the code in a modular way, two specific changes are made:

  • Export the module in tool.js
  • Use modules in index.js

tool.js

It is used to provide a method to export this method for other modules to use, the specific code is as follows:

const updateDom = (id, content) =>{
  document.getElementById(id).innerHTML = content
}
+ export {
+  updateDom
+ }

index.js

Introduce the methods exported in tool.js into index.js. Note that this has already been involved在一个js中引用另一个js

+ import { updateDom } from './tool'
updateDom('app','index.html')

tip: Now that require the use of a modular approach in index.js, so it can not be used directly in the browser, if referenced directly in the index.html in 浏览器会报错.

Next, we need to use webpack commands to process index.js.

webpack packaging

webpack4.x puts forward the slogan of zero configuration packaging: code can be packaged without writing any configuration files. Of course, it has a premise: there is a src/index.js file in the root directory.

The packaging command is:

npx webpack
# 或者是
node_modules/.bin/webpack index.js

If you do not encounter errors, you will see similar results as follows:

Insert picture description here

It shows that the packaging operation has been successful: index.js and tool.js have already 合成had a main.js file.

Two .js files are combined into one .js: the advantage is that it reduces one browser request;

Modularization can be used: The advantage is that it is more convenient to write code.

The schematic is as follows:

Insert picture description here

Insert picture description here

Introduce packaged js

Import the main.js packaged above into index.html

<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <title>index</title>
</head>

<body>
  <div id="app">

  </div>
  <!-- 引入打包后的.js文件 -->
    <script src="../dist/main.js"></script>
</body>

</html>

Okay, now you can see that this code can work normally.

The following is an example diagram.

Insert picture description here

summary

  • webpack can help us improve the front-end development method;
  • It is based on nodejs. Before using it, initialize the project and install webpack locally (different projects may use different versions).
  • It supports zero configuration packaging: the default packaging entry is src/index.js
  • It supports modular writing: there is a mutual reference relationship ( import, export ) between js files .
  • It can package multiple js with reference relationship into one file, and put it in dist/main.js by default .
  • The packaging command is:npx webpack

If there are any shortcomings, please advise, to
be continued, continue to update!
Make progress together!

Guess you like

Origin blog.csdn.net/qq_40440961/article/details/112949385