Home Web Front-end JS Tutorial Introduction to five uses of require

Introduction to five uses of require

Jun 17, 2017 pm 05:22 PM
require introduce usage

This article mainly introduces the detailed explanation of webpack and the five usages of require, which has certain reference value. Interested friends can refer to

webpack. You can write require synchronization syntax in commonjs format, you can write require callback syntax in AMD format, there is also a require.ensure, and webpack's own defined require.include, plus the import syntax of ES6, there are so many It's not going to confuse people. This article will sort out the characteristics of these requirements and the scenarios in which they are used.

commonjs synchronization syntax

The classic commonjs synchronization syntax is as follows:


##

var a = require('./a');
a.show();
Copy after login

At this time webpack will .js is packaged into a file that

references it. This is the most common situation and there is no need to go into details.

commonjs asynchronous loading

There is a

Modules/Async/A specification in commonjs, which defines the require.ensure syntax. Webpack implements it, and its function is to fragment the code during packaging and load the fragmented code asynchronously. The usage is as follows:


require.ensure([], function(require){

  var list = require('./list');

  list.show();

});
Copy after login

At this time list.js will be packaged into a separate chunk file, which may look like this:

1.fb874860b35831bc96a8.js

The readability is relatively poor. I also mentioned at the end of the previous article that the way to name it is to pass the third parameter to require.ensure, such as:



require.ensure([], function(require){

  var list = require('./list');

  list.show();

}, 'list');
Copy after login

You can get the file name you want:

list.fb874860b35831bc96a8.js

You can also pass in a hierarchical name like "question/list", so that webpack will give it according to the hierarchical level. You create folders.

It should be noted that if you reference more than two modules in the

function of require.ensure, webpack will package them together, such as:


require.ensure([], function(require){

  var list = require('./list');

  list.show();

  var edit = require('./edit');

  edit.display();

}, 'list_and_edit');
Copy after login

list.js and edit.js will be packaged into one file and named list_and_edit.js. This needs to be measured based on your actual situation. If you don't want to package them together, you can only write two require.ensure to reference these two files respectively.

One more thing, I actually dislike this kind of thinking. Having to make decisions about packaging during the coding stage obviously violates the principle of separation of duties.

commonjs preloading lazy execution

In the above usage, we passed an empty array to the first parameter of require.ensure, which is actually acceptable here. The function of the module name is to implement preloading and lazy execution. The usage is as follows:


require.ensure(['./list'], function(require){

  var list = require('./list');

  list.show();

});
Copy after login

Pass ['./list'] to the first parameter of require.ensure. When executing here, list.js will be deleted by the browser. After downloading, the code in the list.js module will not be executed, which is what the webpack official website says, and it will not be evaluated. When it comes to actually evaluating, it comes to the following sentence var list = require('./list'); This is the so-called lazy execution.

Multiple modules written in functions will be packaged together, which is no different from the above. In addition, modules written in the array will also be packaged with them, regardless of whether you execute them manually.

This way of writing is also a bit awkward, like a combination of commonjs and AMD, and a module name has to be written twice, which is really not elegant enough. So webpack defines a method of its own to implement preloading.

The require.include that comes with webpack

require.include is provided by webpack itself. There is no specification for the backend, so it plays a small role. It can achieve the above preloading function without writing the module in an array. The usage is as follows:


require.ensure([], function(require){

  require.include('./list');//此处只加载不执行

});
Copy after login

According to the webpack official website documentation, require.include also has another function It can extract the common parts in the sub-module into the parent module. For example, both child1 and child2 refer to the list.js module. Then if list.js is included in the parent, the sub-module will be deleted. , which is equivalent to being promoted to the parent module. (The so-called father-son relationship here refers to the reference relationship)

This method has also been briefly mentioned by the official. It seems to be a useless thing and of little use. Because I found that the return value of require.include is undefined, that is to say, if you want to use the module, the posture is like this:


require.ensure([], function(require){
  require.include('./preview'); //加载
  let p = require('./preview'); //执行
  p.getUrl(); //使用
}, 'pre');
Copy after login

AMD Asynchronous Loading

webpack supports both commonjs specifications and AMD specifications, which means that AMD’s classic syntax can be used normally, such as:


require(['./list'], function(list){

  list.show();

});
Copy after login

Of course, if written like this, list.js will also be packaged into a separate file. Similar to the above, if you write multiple modules here, then these modules will be packaged into one file, such as:


require(['./list', './edit'], function(list, edit){

  list.show();

  edit.display();

});
Copy after login

list.js and edit.js will being packaged together. The difference is that AMD's method cannot pass in the third parameter as the file name, so you cannot get a good-looking file.

ES6 import

这年头不用ES6都不好意思跟人打招呼。所以我们的代码中,又会多一种模块引入语法,那就是import。import会被转化为commonjs格式或者是AMD格式,所以不要把它认为是一种新的模块引用方式。babel默认会把ES6的模块转化为commonjs规范的,你也不用费劲再把它转成AMD了。

所以如下写法是等价的:


import list from './list';

//等价于

var list = require('./list');
Copy after login

不过这两种写法只需选一种,避免在代码中同时使用两种,否则会造成混淆。

总结

以上把require的用法捋了一遍,明白了各自用法的区别之后,我们就可以在项目中进行选择了。我觉得最佳选择是往commonjs方向靠拢,想尝试ES6的话就用import代替commonjs同步语法即可。

因此,代码中保持以下两种风格就好:


//可打包在一起的同步代码,使用import语法

import list from './list';

 

//需要独立打包、异步加载的代码,使用require.ensure

require.ensure([], function(require){

  var list = require('./list');

});
Copy after login

很显然,你在写代码的时候还是需要对打包结果进行决策,这是我不喜欢webpack的原因。gulp那样多好,编码就是编码,编译就是编译,分开来。不过这就是webpack以模块为核心的打包方式的特点吧,仁者见仁,只要团队内做一个约定,也不会打的一塌糊涂。

The above is the detailed content of Introduction to five uses of require. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed introduction to what wapi is Detailed introduction to what wapi is Jan 07, 2024 pm 09:14 PM

Users may have seen the term wapi when using the Internet, but for some people they definitely don’t know what wapi is. The following is a detailed introduction to help those who don’t know to understand. What is wapi: Answer: wapi is the infrastructure for wireless LAN authentication and confidentiality. This is like functions such as infrared and Bluetooth, which are generally covered near places such as office buildings. Basically they are owned by a small department, so the scope of this function is only a few kilometers. Related introduction to wapi: 1. Wapi is a transmission protocol in wireless LAN. 2. This technology can avoid the problems of narrow-band communication and enable better communication. 3. Only one code is needed to transmit the signal

Detailed explanation of whether win11 can run PUBG game Detailed explanation of whether win11 can run PUBG game Jan 06, 2024 pm 07:17 PM

Pubg, also known as PlayerUnknown's Battlegrounds, is a very classic shooting battle royale game that has attracted a lot of players since its popularity in 2016. After the recent launch of win11 system, many players want to play it on win11. Let's follow the editor to see if win11 can play pubg. Can win11 play pubg? Answer: Win11 can play pubg. 1. At the beginning of win11, because win11 needed to enable tpm, many players were banned from pubg. 2. However, based on player feedback, Blue Hole has solved this problem, and now you can play pubg normally in win11. 3. If you meet a pub

Analyze the usage and classification of JSP comments Analyze the usage and classification of JSP comments Feb 01, 2024 am 08:01 AM

Classification and Usage Analysis of JSP Comments JSP comments are divided into two types: single-line comments: ending with, only a single line of code can be commented. Multi-line comments: starting with /* and ending with */, you can comment multiple lines of code. Single-line comment example Multi-line comment example/**This is a multi-line comment*Can comment on multiple lines of code*/Usage of JSP comments JSP comments can be used to comment JSP code to make it easier to read

Usage of WPSdatedif function Usage of WPSdatedif function Feb 20, 2024 pm 10:27 PM

WPS is a commonly used office software suite, and the WPS table function is widely used for data processing and calculations. In the WPS table, there is a very useful function, the DATEDIF function, which is used to calculate the time difference between two dates. The DATEDIF function is the abbreviation of the English word DateDifference. Its syntax is as follows: DATEDIF(start_date,end_date,unit) where start_date represents the starting date.

How to correctly use the exit function in C language How to correctly use the exit function in C language Feb 18, 2024 pm 03:40 PM

How to use the exit function in C language requires specific code examples. In C language, we often need to terminate the execution of the program early in the program, or exit the program under certain conditions. C language provides the exit() function to implement this function. This article will introduce the usage of exit() function and provide corresponding code examples. The exit() function is a standard library function in C language and is included in the header file. Its function is to terminate the execution of the program, and can take an integer

Introducing the latest Win 11 sound tuning method Introducing the latest Win 11 sound tuning method Jan 08, 2024 pm 06:41 PM

After updating to the latest win11, many users find that the sound of their system has changed slightly, but they don’t know how to adjust it. So today, this site brings you an introduction to the latest win11 sound adjustment method for your computer. It is not difficult to operate. And the choices are diverse, come and download and try them out. How to adjust the sound of the latest computer system Windows 11 1. First, right-click the sound icon in the lower right corner of the desktop and select "Playback Settings". 2. Then enter settings and click "Speaker" in the playback bar. 3. Then click "Properties" on the lower right. 4. Click the "Enhance" option bar in the properties. 5. At this time, if the √ in front of "Disable all sound effects" is checked, cancel it. 6. After that, you can select the sound effects below to set and click

PyCharm Beginner's Guide: Comprehensive Analysis of Replacement Functions PyCharm Beginner's Guide: Comprehensive Analysis of Replacement Functions Feb 25, 2024 am 11:15 AM

PyCharm is a powerful Python integrated development environment with rich functions and tools that can greatly improve development efficiency. Among them, the replacement function is one of the functions frequently used in the development process, which can help developers quickly modify the code and improve the code quality. This article will introduce PyCharm's replacement function in detail, combined with specific code examples, to help novices better master and use this function. Introduction to the replacement function PyCharm's replacement function can help developers quickly replace specified text in the code

What is Dogecoin What is Dogecoin Apr 01, 2024 pm 04:46 PM

Dogecoin is a cryptocurrency created based on Internet memes, with no fixed supply cap, fast transaction times, low transaction fees, and a large meme community. Uses include small transactions, tips, and charitable donations. However, its unlimited supply, market volatility, and status as a joke coin also bring risks and concerns. What is Dogecoin? Dogecoin is a cryptocurrency created based on internet memes and jokes. Origin and History: Dogecoin was created in December 2013 by two software engineers, Billy Markus and Jackson Palmer. Inspired by the then-popular "Doge" meme, a comical photo featuring a Shiba Inu with broken English. Features and Benefits: Unlimited Supply: Unlike other cryptocurrencies such as Bitcoin

See all articles