RequireJS Getting Started Guide

Source: Internet
Author: User
Tags define function

Introduction
One of the most common JavaScript libraries today is RequireJS. Recently, I have used RequireJS for every project I have participated in, or I recommend adding RequireJS to them. In this article, I will describe what RequireJS is and some of its basic scenarios.

Asynchronous module definition (AMD)

When talking about RequireJS, you cannot bypass what the JavaScript module is and what AMD is.

The JavaScript module is only a code segment that complies with the Single Responsibility Principle. It exposes a public API. In today's JavaScript development, You can encapsulate many functions in the module, and in most projects, each module has its own file. This makes JavaScript developers a little sad because they need to constantly focus on the dependencies between modules and load these modules in a specific order. Otherwise, errors will occur during runtime.
 

When you want to load the JavaScript module, the script tag will be used. To load the dependent modules, you must first load the dependent modules and then load the dependencies. When using the script tag, you need to arrange their loading in this specific order, and the script loading is synchronized. The async and defer keywords can be used to make loading asynchronous, but the loading sequence may be lost during loading. Another option is to bundle all scripts together, but you still need to sort them in the correct order when bundling.

AMD is such a module definition, so that the module and its dependencies can be asynchronously loaded, but in the correct order.

 

CommonJS is an attempt to standardize the General JavaScript mode. It contains AMD definitions. I suggest you read this article first. In the next version of ECMAScript 6 JavaScript specification, there are normative definitions of the output, input, and module, which will become part of the JavaScript language, and this will not be too long. This is also about RequireJS.
 

RequireJS?
RequireJS is a Javascript file and module framework that can be downloaded from http://requirejs.org/. if you use Visual Studio, you can also obtain it through Nuget. It supports browsers and server environments like node. js. With RequireJS, you can read in sequence only the relevant dependent modules.

What RequireJS does is load the dependencies you define by using the script tag through the head. appendChild () function. After the dependency is loaded, RequireJS calculates the module-defined sequence and calls it in the correct order. This means that you only need to use a "root" to read all the functions you need, and then you only need to hand over the rest to RequireJS. To correctly use these functions, all modules you define must use the RequireJS API. Otherwise, it will not work as expected.
 

The RequireJS API exists in the namespace RequireJS created when requirejs is loaded. Its main APIs are the following three functions:

Define-This function allows you to create a module. Each module has a unique module ID, which is used for the runtime function of RequireJS. The define function is a global function and does not need to use the requirejs namespace.
Require-this function is used to read dependencies. It is also a global function and does not need to use the requirejs namespace.
Config-this function is used to configure RequireJS.
Later, we will teach you how to use these functions, but first let's first understand the loading process of RequireJS.
 

Data-main attributes
After you download RequireJS, the first thing you need to do is to understand how RequireJS starts to work. When RequireJS is loaded, it uses the data-main attribute to search for a script file (it should be the same as loading RequireJS using src ). Data-main needs to set a root path for all script files. According to this root path, RequireJS will load all relevant modules. The following script is an example of using data-main:

1 <script src = "scripts/require. js" data-main = "scripts/app. js"> </script>

Another way to define the root path strength is to use the configuration function. We will see it later. RequireJs assuming that all dependencies are scripts, you do not need to use the. js suffix when declaring a script dependency.
 

Configuration Functions
If you want to change the default configuration of RequireJS to use your own configuration, you can use the require. configh function. The config function needs to input an optional parameter object, which includes many Configuration Parameter options. The following are some configurations you can use:

BaseUrl: the root path used to load the module.
Paths -- used to map the module path under the root path that does not exist.
Shims -- configured outside the script/module and does not use the function dependency of RequireJS and initializes the function. Assume that underscore is not defined using RequireJS, but you still want to use it using RequireJS, You need to define it as a shim in the configuration.
Deps -- load dependency Array
The following is an example of Configuration:

01 require. config ({

02 // By default load any module IDs from scripts/app

03 baseUrl: 'scripts/app ',

04 // doesn't, if the module ID starts with "lib"

05 paths :{

06 lib: '../lib'

07 },

08 // load backbone as a shim

09 shim :{

10 'background ':{

11 // The underscore script dependency shocould be loaded before loading backbone. js

12 deps: ['underscore '],

13 // use the global 'background' as the module name.

14 exports: 'background'

15}

16}

17 });

In this example, the root path is set to scripts/app. Each module starting from lib is configured under the scripts/lib folder, and backbone loads a shim dependency.
 


Defining Modules Using RequireJS
Modules are just well-scoped objects that expose an API and encapsulate their internals. in order to define a module, RequireJS exposes thedefinefunction. there shoshould be only one call fordefinein each JavaScript file by convention. thedefinefunction functions es an array of dependencies and a function which is going to hold all the module definitions. by convention the module definition function since es as parameters all the previous dependencies and in the order they were supplied in the array. for example, here is a simple module definition:

01 define (["logger"], function (logger ){

02 return {

03 firstName: "John ",

04 lastName: "Black",

05 sayHello: function (){

06 logger. log ('hello ');

07}

08}

09}

10 );

As you can see, an array is passed to thedefinefunction with a logger dependency which is later used in the module. also, you can see that in the module definition function there is a parameter calledloggerwhich will be set to the loaded logger module. every module shoshould return its API which in this case is two properties (firstNameandlastName) and a function (sayHello ). later on, if you will load this module as another module dependency with a module ID, you will be able to use the exposed API.
 

Use the require Function
Another very useful function in RequireJS is the require function. The require function is used to load module dependencies but does not create a module. For example, a function that can use jQuery is defined using require.

1 require (['jquery '], function ($ ){

2 // jQuery was loaded and can be used now

3 });

Summary
In this article, I introduced the RequireJS library, which is one of the library functions that I will use to create every Javascript project. It is not only used to load module dependencies and related commands. RequireJS helps us write modular JavaScript code, which is very conducive to code scalability and reusability.
 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.