current position:Home>Hand in hand with you to get started weback4.0 (1)

Hand in hand with you to get started weback4.0 (1)

2022-08-06 19:01:58block concrete mobile engineer

前言

这篇文章是我在学习webpacksome notes from the time,Then some tidying up,This time only a small part of the front,后面会持续更新,对于webpackIt can be said that there are still many little apes who do not know much about it,(ps:I am also a little ape),But in many interviews, companies will ask job applicants to know somewebpackThe basic configuration and some optimizations to the project,This forces us to learn,Hope this note will be useful to just learningwebpackThe children's boots are helpful

什么是webpack?webpack能做什么?

webpack 是一个用于现代 JavaScript 应用程序的 静态模块打包工具.Multiple modules used in a project can be packaged into one or more packages,webpackMore applications are also reflected in the project optimization

Let's initialize a project

First create a new directory folder,Then open a command window to usenpm init来创建一个package.jsonto record downloaded packages,然后安装依赖包webpackwebapck-cli,我这里使用的是npm,使用yarn也是可以的

npm i webpack webpack-cli -D
复制代码

One will be generated after running the command successfullypackage.json,First add a packing instruction to it,来运行打包,Packaging will look for it by defaultsrc目录下的index.js,

package.json下配置:

 "scripts": {
    "build":"webpack"
  },
复制代码

image.png

So we first create a new one in the directorysrc文件夹并创建一个index.js,Write some code in it,

image.png

console.log('webpack打包');
复制代码

Let's try it out by running the package command

npm run build
复制代码

This prompt will appear after execution,原因是没有指定mode导致的,It will be configured step by step later,先忽略掉,If one is generated in your directorydist文件夹,里面有一个main.js就说明打包成功了

image.png

image.png

entry和output

The package export entries above are all default,The entry default issrc下的index.js,Export is by defaultdist下的main.js,Of course, we can customize the export entrance

entry:配置打包入口文件 output:配置打包出口文件,output是个对象,There are two required properties:pathThe name of the export path folder,filenameThe name of the export file

Single entry, single output

创建一个webpack.config.js,配置如下:

const path = require('path');

module.exports = {
  entry: './src/main', //指定入口文件
  output: { // 指定出口
    path: path.resolve(__dirname, 'dist'), // The name of the export path folder
    filename: 'bundle.js', // The name of the export file
  },
};
复制代码

Let's run the package command again

npm run build
复制代码

The packaged files are generated as follows,Then we have successfully configured the specified exit entry

image.png

Multiple entry single output

When we need to specify multiple entry files,When exporting a single file,It can be configured by means of an array

entry: ['./src/main','./src/main2.js'],
复制代码

这个时候在main.js里面写了一个sayfunction and created onemain2.js也写了一个say函数调用,Pack them together,New folderpublic里面创建index.html进行引用,See if the output is packaged successfully

main.js

const say = () => console.log('main.js');
say()
复制代码

main2.js

const say = () => console.log('main2.js');
say()
复制代码

运行打包命令

npm run build
复制代码

Normal output after running

image.png

多入口多输出

When we need to configure multiple entries,entryThe value is represented in the form of an object(也可以为数组),key对应的是chunkname,valueThe corresponding is to specify the entry file path

 entry: {
    main: './src/main.js', // 我们配置的chunkname
    main2: './src/main2.js'
  },
复制代码

When configuring multiple outputs,outputconfiguration can not befilename写死,webpack提供了[name]占位符,可以自动将chunkname的值进行替换,Click for detailed explanation官方文档查看

 output: { // 指定出口
    path: path.resolve(__dirname, 'dist'), 
    filename: '[name].js', // will be automatically replaced with the configured onechunkname
  },
复制代码

Package it up and run it

npm run build
复制代码

Run if the corresponding file is generated,就说明成功了

image.png

mode

The 'mode' option has not been set, webpack will fallback to 'production' for this value.
Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/

复制代码

Next, solve the warning prompt problem left before,原因是没有指定mode,在没有指定mode情况下,默认是production生产模式,可以利用process.env.NODE_ENVto determine which environment the user is in,然后改变modeThe value of the package is differentiated,modeConfiguration provides three values,详情可点击[官方文档]

(webpack.docschina.org/configurati…

  • development:开发模式,It is helpful for us to develop and debug,Compared with the production model, the volume is larger
  • production :生产模式,The volume will be small,But it is not conducive to development and debugging
  • none:不使用任何默认优化选项 mode配置:
const path = require('path');

module.exports = {
  entry: {
    main: './src/main.js',
    main2: './src/main2.js'
  }, 
  output: {
    path: path.resolve(__dirname, 'dist'), 
    filename: '[name].js', 
  },
  mode:'development' // 开发模式
};
复制代码

插件

插件PluginsIt can help us to pack better,Optimize your own projects,可以说是很香了

image.png

HtmlWebpackPlugin

We packed it beforejs需要我们手动创建HTML来引入使用,现在它HtmlWebpackPlugin来了,简化了 HTML 文件的创建,We can preview the web page after running the project directly,首先下载HtmlWebpackPlugin依赖包

npm i html-webpack-plugin -D
复制代码

首先我在src下面创建了一个HTML文件,Based on this file to package,配置如下:

const path = require('path');
// 导入插件
const HtmlWebpackPlugin = require('html-webpack-plugin');
// Create a plugin instance for configuration
const htmlPlugin = new HtmlWebpackPlugin({
  template: './src/index.html', // Specifies the template to use
  filename: 'index.html' // The generated template name
})
module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: './src/main.js',
  },
  // 编译模式
  mode: 'development', // 开发模式
  plugins: [htmlPlugin] // Plugins是个数组,The plugins used need to be placedPlugins数组里面
};
复制代码

输出结果:

image.png

webpack-dev-server

After we packaged the project before,Change the file again,You need to repackage to see the effect,webpack-dev-server It can support automatic packaging of our project,After packaging and changing the file, you only need to refresh the browser to view the latest code,首先下载依赖包

npm i webpack-dev-server -D
复制代码

package.json配置如下

"scripts": {
    "dev": "webpack-dev-server"
  },
复制代码

运行npm run dev After visiting the local address, you can view the effect of automatic packaging

image.png

Configuration related to automatic packaging

After configuring automatic packaging, it can be packaged in real time,But we still need to access it manually,At this time, there are the following configurations

  • --open :打包完成后自动打开浏览器页面
  • --host :配置IP地址
  • --port :配置端口号
 "scripts": {
    "dev": "webpack-dev-server --open --host 127.0.0.1 --port 8888"
  },
复制代码

copyright notice
author[block concrete mobile engineer],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/218/202208061858275357.html

Random recommended