JavaScript's Requirejs Library starter Guide

Source: Internet
Author: User
Tags define function require script tag visual studio

This article mainly introduces the JavaScript Requirejs library Getting Started Guide, Requirejs Library's popularity recently climbed quickly, needs the friend to be possible to refer to under

Brief introduction

One of the most common JavaScript libraries today is Requirejs. Every project I've been involved in recently has been used for Requirejs, or I've recommended adding requirejs to them. In this article, I'll describe what Requirejs is, and some of its underlying scenarios.

Asynchronous module definition (AMD)

Talking about Requirejs, you can't get around to mentioning what JavaScript modules are, and what AMD is.

The JavaScript module simply follows the code snippet for the SRP (single responsibility principle sole responsibility principle), exposing a public API. In today's JavaScript development, you can encapsulate many features in a module, and in most projects, each module has its own files. This makes JavaScript developers feel a bit sad because they need to constantly focus on dependencies between modules, loading the modules in a specific order, or releasing errors at runtime.

The script tag is used when you want to load a JavaScript module. In order to load dependent modules, you must first load the dependent, then load the dependent. When you use the script tags, you need to schedule their loading in this particular order, and the scripts are loaded synchronously. You can use the async and defer keywords to make the load asynchronous, but you may lose the order of loading during the load. Another option is to pack all the script bundles together, but you still need to sort them in the correct order when tying.

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

COMMONJS, a standardized attempt on the generic JavaScript model, contains the AMD definition, and I suggest you read it before continuing with this article. In the next version of the JavaScript specification in ECMAScript 6, there are specification definitions for output, input, and modules that will become part of the JavaScript language, and it won't be long. It's also about Requirejs what we want to say.

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 get it through NuGet. It supports browsers and server environments such as Node.js. Using Requirejs, you can read sequentially only dependent modules are required.

What Requirejs do is load these dependencies through the Head.appendchild () function when you use the script tag to load the dependencies you define. After dependency loading, Requirejs calculates the order of the module definitions and calls in the correct order. This means that all you need to do is use a "root" to read all of the features you need, and then the rest of the thing just needs to be given to Requirejs. To properly use these features, all of the modules you define need to use the Requirejs API, or it will not work as expected.

The Requirejs API exists under the namespace Requirejs created when Requirejs is loaded. The main APIs are the following three functions:

define– the function user to create the module. Each module has a unique module ID, which is used for Requirejs run-time functions, and the Define function is a global function that does not require the use of Requirejs namespaces.

require– This function is used for read dependencies. It is also a global function and does not require the use of the Requirejs namespace.

config– This function is used to configure Requirejs.

In the back, we'll teach you to use these functions, but first let's look at the loading process for the next Requirejs.

Data-main Property

When you download Requirejs, the first thing you need to do is to understand how Requirejs started to work. When Requirejs is loaded, it uses the Data-main property to search for a script file (it should be the same script as loading Requirejs with SRC). Data-main need to set a root path for all the script files. Depending on the root path, REQUIREJS will load all the associated modules. The following script is an example of using Data-main:

  

Another way to define root-road strength is to use a configuration function, which we'll see later. Requirejs assumes that all dependencies are scripts, you do not need to use the. js suffix when you declare a script dependency.

Configuration functions

If you want to change the REQUIREJS default configuration to use your own configuration, you can use the Require.configh function. The config function needs to pass in an optional parameter object that includes a number of configuration parameter options. Here are some of the configurations you can use:

baseurl--is used to load the root path of a module.

paths--is used to map a module path that does not exist under the root path.

The shims--configuration is outside the script/module and does not use Requirejs function dependencies and initializes the function. Suppose underscore does not use the REQUIREJS definition, but you still want to use it through REQUIREJS, then you need to define it as a shim in the configuration.

deps--Load Dependencies Array

Here is an example of using a configuration:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16-17 Require.config ({//by default load any module IDs from Scripts/app baseurl: ' Scripts/app ',//except, if the module ID star TS with "Lib" Paths: {lib: ' ... /lib '},//load backbone as a shim shim: {' backbone ': {//the underscore script dependency should be loaded before ng backbone.js deps: [' underscore '],//Use the global ' backbone ' as the module name. Exports: ' Backbone '}});

In this example, the root path is set to Scripts/app, each module started by LIB is configured under the Scripts/lib folder, and backbone loads a shim dependency.

Defining modules with Requirejs

The module is an object which carries on the internal implementation encapsulation, exposes the interface and the reasonable limit scope. Reuqirejs provides a define function for defining modules. By chapter conventions each JavaScript file should only define one module. The Define function accepts an array of dependencies and a function that contains the definition of a module. Typically, a module definition function takes the dependent modules in the preceding array as parameters in order to receive them. For example, here is a simple module definition:

?

1 2 3 4 5 6 7 8 9 10 Define (["Logger"], function (logger) {return {firstName: "John", LastName: "Black", Sayhello:function () {Logger.log (' H Ello '); } } } );

We see that a module-dependent array containing logger is passed to the Define function, which is later invoked. Also, we see that the defined module has a parameter named logger, which is set to the Logger module. Each module should return its API. In this example we have two attributes (FirstName and LastName) and one function (SayHello). Then, as long as the module you defined later uses the ID to refer to the module, you can use its exposed API.

Using the Require function

Another very useful function in Requirejs is the Require function. The Require function is used to load a module dependency but does not create a module. For example: The following is a function that uses require to define the ability to use jquery.

?

1 2 3 Require ([' jquery '], function ($) {//jquery was loaded and can is used now});

Summary

In this article I introduced the Requirejs library, which is one of the library functions I'll use to create every JavaScript project. Not only is it used to load module dependencies and related commands, Requirejs helps us write modular JavaScript code, which is very beneficial to the scalability and reusability of the code.

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.