webpack - basic usage and summary of webpack

1. The concept of webpack

what is webpack

  1. Webpack front-end resource modular management and packaging tool. Many loose modules can be packaged into front-end resources that conform to production environment deployment according to dependencies and reference relationships. Separate the code of the modules loaded on demand, and load them when they are actually needed.

  2. webpack is a package running on the node environment; webpack can treat any front-end resource as a module for packaging and integration, and can also support different codes (ES6 module code, CSS files, LESS files, pictures...) After writing the front-end code , can be packaged and integrated by webpack, and run on the browser;

2. Why learn webpack

  1. A development environment is needed for development. It would be great if the browser automatically displays the latest code after we modify the code and save it;
  2. ​When writing code locally, it would be fine if the interface of the backend is not cross-domain (proxy service);
  3. In order to keep up with the times, it would be great if we could use new things such as ES6 (translation service);
  4. The project is about to go online, it would be great if you can compress the code and pictures with one click (compression and packaging service);

3. Features of webpack

  1. Rich plug-ins, popular plug-ins, convenient for development work;
  2. A large number of loaders are convenient for processing and loading various static resources;
  3. Separate the code of the modules loaded on demand, and load them asynchronously when they are actually needed;

4. Advantages over other tools

Advantages over other module packaging tools (Grant/Gulp),

  1. Webpack writes scripts in the form of CommonJS, and supports AMD / CMD / ES6 modules comprehensively, which is convenient for code migration of old projects. All resources can be modularized;
  2. It is easy to develop and can replace the work of Grunt / Gulp, such as packaging js/css, packaging and compressing images, CSS separation, code compression, etc. Strong scalability, perfect plug-in mechanism, support module hot replacement, etc.;

5. Preparation

1. Install node and npm
node is the environment where nodejs runs, and npm is a package manager tool installed together with node, which can easily manage all the third-party dependent packages we need

2. Install the webpack module

​ webpack is usually installed using the npm package management tool. The stable version released by webpack is now webpack4;
the command to install webpack globally:npm install webpack -g

Order Installation Environment Remark
npm view webpack versions --json do not install, view View the version numbers of all webpack modules now
npm install webpack -g -g install globally
Install webpack globally
and use the webpack command on your computer (the tool module needs to be global)
webpack -v Do not install, check the global webpack version number (note, webpack4.x version, you need to install the webpack-cli tool to run this command) Possible problems:
1. webpack is not an internal or external command (proves that your global installation failed/the configuration of the computer's environment variable node is invalid)

3. Install the webpack-cli toolkit
Most of the webpack commands will execute the Api method in the webpack-cli to achieve specific functional effects, so the webpack4.x version needs to install this module globally, while webpack3.x does not extract it Those API methods come out, so webpack3.x does not need to install this module;

​ command:npm i webpack-cli -g

Note that webpack4 matches webpack-cli3.x version

4. Explanation of two environments

  • Local development environment (development): When we write code locally;
  • Online publishing environment (production): We have developed the code locally, packaged it, and released it to the outside world;

6. The core introduction of webpack

1. Key note: webpack.config.js file

​ Webpack provides developers with a configuration information entry for program packaging, allowing developers to better control and manage the packaging process of the program and the output of the final program. The default webpack configuration file is webpack.config.js, run the webpack packaging command, it will automatically check the webpack.config.js file in the directory where the command is run;

Note: webpack4.x version can omit this file, webpack3.x version must declare this file

2. Core concept explanation
Official website link: https://www.webpackjs.com/concepts/

Conceptual name of webpack explain
entry point The base directory specifies the "./src" directory, then the relative paths used in all the following configurations start from src
Entrance The entry point indicates which module webpack should use as the start of building its internal dependency graph
. After entering the point, webpack will find out which modules and libraries the entry point depends on (directly and indirectly)
exit output tells webpack where to output the results it creates and how to name the files. The default is./dist
Loader The loader allows webpack to process non-JavaScript files (webpack itself only understands JavaScript). The loader can convert all types of files into valid modules that webpack can handle,
and then you can use webpack's packaging capabilities to process them.
plug-in Loaders are used to transform certain types of modules, while plugins can be used to perform a wider range of tasks.
Plugins range from packaging optimization and compression, all the way to redefining variables in the environment.
The plug-in interface is extremely powerful and can be used to handle a wide variety of tasks.
model By developmentselecting productionone of or to set modethe parameter ,
you can enable the built-in optimization of webpack in the corresponding mode

3. Explanation of configuration file parameters Official
website link: https://www.webpackjs.com/configuration/

key name concept explain
context entry point Base directory, absolute path , used to resolve the entry point from the configuration
entry entrance (required) Configure the name of the package entry file
output export (required) Where to output after packaging, and the output file name
module loader configuration In the corresponding array of rules, define the object rules
plugins plugin configuration Configure plug-in functions
mode model Select online/offline environment mode
devtool development tools How to generate a source map and record the number of lines in the file where the code is located (debugging mode)

7. Use webpack - package js code

1. Package js code

  1. Prepare the front-end module js file, and the main entry file main.js (customized name), and use the front-end packaged module in the main entry file
  2. Declare the webpack configuration file of webpack.config.js in the current project directory, and fill in the configuration object information (required for entry + exit)
    • dist will be created automatically if it does not exist
    • The value of output.path must be an absolute path (because webpack creates the dist directory from the global, so it must start from the global)
  3. Execute the webpack packaging command in the current project directory to view the packaged js file generated by the export
  4. Create a new index.html file by yourself to import the packaged js, and execute it to view the effect

The webpack command will automatically search for the webpack.config.js configuration file in the directory where the current command is located, and package the code according to the configuration file

2. Single entry – single exit

  1. Single entry, you can introduce many module parts to be used, single entry (referring to the entry file specified when packaging)
  2. A single export refers to packaging all js, and finally input them into a separate .js file for use
module.exports = {
    
    
    context: __dirname + "/src", // 拼接src的绝对路径, context设置入口的文件前缀, 代表入口要从这个文件夹开始寻找 (必须是绝对路径) __dirname: 指的当前文件所在文件夹的路径路径
    entry: "./main.js",
    output: {
    
    
        path: __dirname + '/dist', // 给我输出到同级下的dist目录中(如果没有会自动创建)
        filename: 'bundle.js' // 输出js文件的名字
    }
};

3. Multiple entrances – single exit

1. Multiple entries: tell webpack which files to package

module.exports = {
    
    
    context: path.resolve(__dirname, "src"),
    entry: ["./main.js", "./center.js"], // 设置多入口文件路径
    output: {
    
    
        path: __dirname + '/dist',
        filename: 'bundle.js'
    }
};

4. Multiple entrances – multiple exits

module.exports = {
    
    
    context: path.resolve(__dirname, "src"),
    entry: {
    
    
        "first": "./main.js",
        "second": "./center.js"
    }, // 如果是多入口单出口用数组结构, 如果是多入口, 多出口用对象结构, 而且key值是打包后的文件名
    output: {
    
    
        path: __dirname + '/dist',
        filename: '[name].js' // [name]是webpack内置的字符串变量, 对应entry里每个key
    }
}

8. Package css code

  1. Need to download 2 loader modules (the purpose is to let webpack recognize css files)
    • css-loader: Receive a css file, and reduce a version when downloading cssloader by parsing the import method @3 The downloaded version is 3.6
    • style-loader: receive css code and inject it into html webpage
  2. In webpack.config.js, loader configuration:
module: {
    
     // 对加载器进行配置
	rules: [ // 加载器的使用规则
		{
    
     // 独立的规则对象
			test: /\.css$/, // 以.css结尾的文件类型
			use: [ 'style-loader', 'css-loader' ] // 使用哪些加载器进行转换 
			// 注意:  2个加载器的顺序, 默认是从右往左进行使用
		}
	]
}
  1. Introduce the css module in the entry file
import "./style/home.css" // 注意无需用变量接收
  1. The css code will be packaged into the js file in the form of a string

  2. Create a new index.html under dist, just import the packaged bundle.js to see the effect of css code packaged into js

9. Generate html files

  1. 1 plugin module required to download
    • html-webpack-plugin: HtmlWebpackPluginSimplifies the creation of HTML files, you can let the plugin generate an HTML file for you, use the default template, or use your own specified template
  2. webpack.config.js plugin configuration
const HtmlWebpackPlugin = require("html-webpack-plugin");
plugins: [ // 配置各种插件
	new HtmlWebpackPlugin({
    
     // 插件配置对象
		title: "webpack ldx使用",
		filename: "index.html", // 产出文件名(在dist目录查看)
		template: __dirname + "/index.html", // 以此文件来作为基准(注意绝对路径, 因为此文件不在src下)
		inject: true, // 代表打包后的资源都引入到html的什么位置
		favicon: "./assets/favicon.ico", // 插入打包后的favicon图标
		// base: "./", // html网页中所有相对路径的前缀 (一般不给/给./, 虚拟路径)
		// 控制html文件是否要压缩(true压缩, false不压缩) 
        minify: {
    
                                 //对html文件进行压缩,
                collapseBooleanAttributes: true,  //是否简写boolean格式的属性如:disabled="disabled"简写为disabled
                collapseWhitespace: true,         //是否去除空格,默认false
                minifyCSS: true,                  //是否压缩html里的css(使用clean-css进行的压缩) 默认值false
                minifyJS: true,                   //是否压缩html里的js(使用uglify-js进行的压缩)
                removeAttributeQuotes: true,      //是否移除属性的引号 默认false
                removeComments: true,             //是否移除注释 默认false
                removeCommentsFromCDATA: true,    //从脚本和样式删除的注释, 默认false
                useShortDoctype: true             //使用短的文档类型,将文档转化成html5,默认false
         }
	}) // 数组元素是插件new对象
]
  1. src/index.html static web page template
  2. Execute the webpack packaging command, observe whether the xxx.html file is added in the directory generated by dist, and all required external resources will be automatically introduced

report error

Cannot find module “webpack/lib/node/NodeTeplatePlugins”

In the project where the html-webpack-plugin plugin is installed, install the version corresponding to the global webpack separately locally

The plug-in configuration items are as follows:

option key value type Defaults explain
title String Webpack App In generating html web pages标签里的内容 (如果指定template选项, 则此选项失效
filename String index.html The name of the generated html web page file (directory + name can also be set)
template String Which existing html file is used as the basic template, based on this template, the html web page file is generated
inject Boolean/String true Range of values ​​(true || 'head' || 'body' || false)
true/'body' -> script and other import codes, put them at the end of the body tag
'head'/false -> script and other import codes, put to the end of the head tag
favicon String Insert the path of the favicon.ico icon into the html web page
base String All relative paths in html are based on its value as the starting point, for example: the value of base is /bar/, then the img in your HTML page, src="my.img", the actual path to find is actually /bar/my.img
minify Boolean Look at the value of mode Whether to compress the html code, if the mode is 'production', then the value of minify is true, otherwise it is false

10. Separate css code

  1. Need to import 1 plug-in module,

    • extract-text-webpack-plugin using the next version @next will move all references in the entry *.cssto a separate CSS file. Therefore, your styles will no longer be embedded in the JS, but will be placed in a separate CSS file. If your stylesheets are large, this will make them load faster since the CSS will be loaded in parallel with the JS.
    • This plugin does not have the function of compressing css code
  2. webpack.config.js loader modification

const ExtractTextPlugin = require("extract-text-webpack-plugin"); 
rules: [ // 加载器的使用规则
	{
    
    
		test: /\.css$/,
		use: ExtractTextPlugin.extract({
    
     // 从一个已存在的 loader 中,创建一个提取(extract) loader。
			fallback: "style-loader",  // 应用于当CSS没有被提取(正常使用use:css-loader进行提取, 如果失败, 则使用fallback来提取)
        	use: "css-loader"  // loader被用于将资源转换成一个CSS单独文件
        })
	}
]
  1. Plug-in configuration: Other options can be defaulted

    new ExtractTextPlugin("style.css"), // 输出的文件名
    
  2. In the directory generated by dist packaging, a separate .css file will be separated

report error

Chunk.entrypoints: Use Chunks.groupsIterable and filter by instanceof Entrypoint instead

“extract-text-webpack-plugin”: “^3.0.2” 此插件3.x版本对应webpack3.x, 所以我们需要更高的extract版本, 所以下载extract-text-webpack-plugin@next (@next下载下一个内测最新版)

11,打包less

  1. 需要安装less 和 less-loader 来解析less代码, 和加载less文件

    ​ npm install less

    ​ npm install less-loader

  2. 在webpack.config.js中 配置加载器, 解析.less文件

    {
          
           
    	test: /\.less$/, 
    	use: ['style-loader', 'css-loader', "less-loader"]
    }
    
  3. 但是这样发现css代码没有分离出来, 所以还需要使用extract-text-webpack-plugin的配置, 分离出css代码

    {
          
           
    	test: /\.less$/, 
    	use: ExtractTextPlugin.extract({
          
           
    		fallback: "style-loader", 
    		use: ['css-loader', "less-loader"]
    	})
    }
    
  4. 观察打包后style.css中多了less文件里的样式代码

12,集成postcss

1,什么是postcss

是一个转换 CSS 代码的工具和插件 (postcss转换css代码, 为了兼容不同的浏览器)
类似于babel.js把浏览器不兼容的js转换成兼容的js代码 (babel转换js代码, 为了兼容不同浏览器)
注意它本身是一个工具, 和less/sass等预处理器不同, 它不能处理css代码
而是靠各种插件来支持css在不同浏览器和环境下正确运行的

  • 增加可读性, 会自动帮你添加特定浏览器厂商的前缀 (插件: autoprefixer)
  • px单位自动转rem (插件: postcss-pxtorem)
  1. 先下载postcss-loader 和postcss到当前工程中
    npm install postcss
    npm install postcss-loader@3
  • postcss: 集成这个工具, 可以让它发挥它集成的翻译css的插件
  • postcss-loader: 对css文件进行处理
  1. 新建webpack.config.js同级的postcss.config.js 配置文件
  2. 去webpack.config.js中, 把postcss使用到css相关的加载器中
{
    
     
	test: /\.css$/, 
	use: ExtractTextPlugin.extract({
    
     
		fallback: "style-loader", 
		use: [{
    
     
			loader: 'css-loader', 
			options: {
    
     importLoaders: 1 } 
		}, "postcss-loader"]
	})
	// importLoaders 用于配置「css-loader 作用于 @import 的资源之前」有多少个 loader。
},

2,autoprefixer

在css和less文件中, 准备一些代码
自动补全前缀:

1.先下载此插件模块: npm i autoprefixer@9
2.postcss.config.js 配置如下:

module.exports = {
    
    
  plugins: {
    
     // postcss在翻译css代码的时候, 需要使用哪些插件功能
    // 1. 写使用插件模块的名字, postcss会自己去require引入
    // 2. 必须配置浏览器列表才可以 自动添加前缀
    'autoprefixer': {
    
    
      // 浏览器支持列表放到了package.json中browserslist中进行编写
    }
  }
}

package.json的browserslist下设置

"browserslist": [ 
    "defaults", 
    "not ie < 11", 
    "last 2 versions", 
    "iOS 7", 
    "last 3 iOS versions" 
]
// defaults相当于 "> 5%", 国内浏览器使用率大于5%的
// not ie < 11  不兼容IE11以下的浏览器 (支持ie11)
// 支持最后2个版本
// iOS苹果手机操作系统, 支持ios7
// 支持最后3个IOS的版本 ios13, 12, 11
  1. 打包观察生成的style.css文件中代码是否拥有浏览器兼容的前缀

3,postcss-pxtorem

浏览 && 画图, 解释rem 如何适配的
此插件是自动把(css/less…文件里 px转换成适配的rem单位), 无需再手动计算了

  1. 先下载此插件模块 npm i postcss-pxtorem
  2. 在postcss.config.js中配置如下,
'postcss-pxtorem': {
    
    
	rootValue: 16, // 这个值就是你看设计稿上基准字体是多少, 就写多少, 1rem=16px
	unitPrecision: 6, // 小数点几位
	propList: ['*'], // 指定需要转换rem的属性 例如: 'font-size' 'line-height' *代表所有属性
	mediaQuery: false, // 媒体查询的px是否转换
	minPixelValue: 0, // 小于指定数值不转换
	// 默认px识别大写小, 所以不写成px不转换
}

注意: 只对css/less文件内代码有效, 因为webpack.config.js中, 加载器使用了postcss-loader

注意: 如果html中使用px转rem, 可以安装插件, 来自动把px转换成rem使用

注意: html的font-size不会自动随着网页的变化而变化

  1. 在index.html模板文件中, 根据当前网页设置html的fontSize, 来让所有rem单位在运行时得到真正的像素大小

13,压缩css文件

想要压缩打包后的css文件, 可以使用 optimize-css-assets-webpack-plugin, 先下载这个插件,在webpack.config.js中配置

const OptimizeCss = require('optimize-css-assets-webpack-plugin');
plugins: [ // 新增
    new OptimizeCss()
]

14,打包_assets

  1. 需要引入2个加载器模块,
    • url-loader: url-loader 功能类似于 file-loader,但是在文件大小(单位 byte)低于指定的限制时,可以返回一个 DataURL(base64字符串)
    • file-loader: 产出, 寻找文件的引用位置
  2. 准备工作: 注意打包的资源, 都要和入口文件产生直接/间接关系, 所以不要写在index.html模板文件中, 那样是不会被webpack处理的
    • assets 下准备 图片 和字体图标
    • 在main.js中, 创建标签, 使用图片/字体图标样式

注意: webpack认为, 图片也是一个模块, 所以才需要loader来解析图片, 所以图片需要import/require引入)

  1. webpack.config.js加载器配置:
/*{
	test: /\.(png|jpg|jpeg|gif|svg)$/,
	use: [
		{
			loader: 'url-loader',
			options: { // 参数
				limit: 8192 // 8kb内的文件都转换成DataURL, 如果超出的都转换成base64字符串
			}
		}
	]
},
*/
// 上面options可以简写成下面?传参数的格式
{
    
    
	test: /\.(png|jpg|jpeg|gif|svg)$/, // 处理这些结尾的文件
                use: [
                    {
    
       // options传参的方式被我改成了?传参
                        // ? 代表给加载器传入配置参数
                        // limit字段: 对打包的图片限制字节大小为8KB以内, 超出此限制,会被file-loader产生一个文件
                        // [name]: 代表直接使用打包目标文件的名字,
                        // [ext]: 代表直接使用打包目标文件的扩展名
                        // name字段: 代表给打包后的文件定义名字(可以使用[]这种规则)
                        // 8KB
            loader: 'url-loader?limit=8192&name=assetsDir/[name].[ext]'
         }
	]
}
// 如果处理字体图标需要引入这个
{
    
    
	test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
	loader: 'url-loader',
	options: {
    
    
		limit: 10000,
		name: 'fonts/[name].[hash:7].[ext]'
	}
}
  1. 执行打包命令, 查看dist目录中和index.html中的效果

总结: 小于limit限制的assets下的图片资源, 都会被打包进js文件中, 先被url-loader转换成了base64字符串 (这种加密方式的字符串, 可以被img标签的src所接受, 但是一定要在base64加密的字符串前, 声明一个表示 data:image/png;base64, 后面跟base64字符串)

15.使用总结

​找插件/加载器, 下载插件/加载器模块, webpack.config.js中进行配置, 编码/准备资源, 打包, 把打包后的资源部署到服务器上;

​部署: 配置环境和需要的各种软件参数等, 上传代码资源包

16,node常用的方法/变量

  • __dirname (注意2个下划线): 代表当前文件所在文件夹的 绝对路径

  • path.resolve: 合并2个路径

17,webpack的作用是什么,谈谈你对它的理解

答案: 现在的前端网页功能丰富,特别是SPA(single page web application 单页应用)技术流行后,JavaScript的复杂度增加和需要一大堆依赖包,还需要解决SCSS,Le…新增样式的扩展写法的编译工作。所以现代化的前端已经完全依赖于WebPack的辅助了。

现在最流行的三个前端框架,可以说和webpack已经紧密相连,框架官方都推出了和自身框架依赖的webpack构建工具。

· React.js+WebPack

· Vue.js+WebPack

· AngluarJS+WebPack

webpack的工作原理?

答案: WebPack可以看做是模块打包机:它做的事情是,分析你的项目结构,找到JavaScript模块以及其它的一些浏览器不能直接运行的拓展语言(Sass,TypeScript等),并将其转换和打包为合适的格式供浏览器使用。在3.0出现后,Webpack还肩负起了优化项目的责任。

webpack插件网址
https://www.webpackjs.com/plugins/

webpack加载器网址
https://www.webpackjs.com/loaders/

Guess you like

Origin blog.csdn.net/qq_43886365/article/details/129303788