Download and install
To use SEAJS in your project, all you need to do is download the sea.js and put it in a location on your project.
The SEAJS project is currently hosted on GitHub, and the home page is https://github.com/seajs/seajs/. You can download sea.js (compressed) or sea-debug.js (uncompressed) in the build directory of its git library.
When the download is complete, put it in the appropriate position on the project, and then introduce it through the <script> tag in the page, and you can use SEAJS.
SEAJS Basic principles of development
Before discussing the concrete use of SEAJS, first introduce the modular concept and development principle of SEAJS.
The basic principle of using SEAJS to develop JavaScript is that everything is a module. When SEAJS is introduced, writing JavaScript code becomes the writing of one module after another, the concept of the module in Seajs is somewhat similar to the Object-oriented class--modules can have data and methods, data and methods can be defined as public or private, and public data and methods can be invoked by other modules.
In addition, each module should be defined in a separate JS file, that is, a corresponding module.
The following is an introduction to the writing and invocation of modules.
Definition and compilation of modules
Module definition function define
A module is defined using the "define" function in Seajs. Because the SEAJS document does not have a complete reference to define, I read the SEAJS source code and found that define can receive three parameters:
Copy Code code as follows:
/**
* Defines a module.
* @param {string=} ID the module ID.
* @param {array.| string=} deps the module dependencies.
* @param {function () | Object} factory the module factory function.
*/
Fn.define = function (ID, deps, factory) {
Code of Function ...
}
The above is I extracts from the SEAJS source code, define can receive parameters are module ID, dependent module array and factory function. When I read the source code, I found that the parsing rules for the number of different parameters are define:
If there is only one argument, the value is assigned to factory.
If there are two arguments, the second assignment is given to factory; the first one, if it is an array, is assigned to Deps, otherwise assigned to the ID.
If there are three parameters, the values are assigned to Id,deps and factory respectively.
However, the official example of SEAJS, where almost all define are used, passes only one factory function, similar to the following code:
Copy Code code as follows:
Define (function (Require, exports, module) {
Code of the module ...
});
Personal advice is to follow the SEAJS official example and define the module with the define of a parameter. So what do IDs and Deps do with it?
ID is the identity string of a module, define only one parameter, the ID will be assigned by default to this JS file absolute path. If you use define to define a module in the A.js file under example.com, the ID of the module is assigned to Http://example.com/a.js and there is no special recommendation not to pass in the ID. Deps generally do not need to be passed in, the module needs to use the require load.
Factory Analysis of Factory function
The factory function is the main body and the key point of the module. When passing only one parameter to define (recommended notation), this parameter is the factory function, at which point the three parameters of the factory function are:
1.require--module loading function for documenting dependent modules.
2.exports--an interface point that exposes the data or method to an external call.
3.module--the module's metadata.
These three parameters can optionally select whether to display the specified.
Let's say module. A module is an object that stores meta information for modules, as follows:
ID of the 1.module.id--module.
2.module.dependencies--an array that stores the list of IDs for all modules that this module relies on.
3.module.exports--and exports point to the same object.
Three modes of writing modules
The first mode of defining a module is based on the exports pattern:
Copy Code code as follows:
Define (function (Require, exports, module) {
var a = require (' a '); Introducing a module
var B = require (' B '); Introduce B module
var data1 = 1; Private data
var func1 = function () {//Private method
Return A.run (DATA1);
}
EXPORTS.DATA2 = 2; Public data
EXPORTS.FUNC2 = function () {//Public method
return ' Hello ';
}
});
The above is a more "authentic" module definition pattern. In addition to attaching public data and methods to exports, you can also directly return an object representation module, as the following code functions the same as the code above:
Copy Code code as follows:
Define (function (require) {
var a = require (' a '); Introducing a module
var B = require (' B '); Introduce B module
var data1 = 1; Private data
var func1 = function () {//Private method
Return A.run (DATA1);
}
return {
Data2:2,
Func2:function () {
return ' Hello ';
}
};
});
If the module definition has no other code and returns only one object, you can also make the following simplified notation:
Copy Code code as follows:
Define ({
Data:1,
Func:function () {
return ' Hello ';
}
});
The third approach is appropriate for modules that define pure JSON data.
Loading and referencing of modules
The addressing algorithm of the module
The above mentioned a module corresponding to a JS file, and load the module is generally to provide a string parameter to tell the Load function required module, so you need a set from the string identification to the actual module is the file path of the resolution algorithm. SEAJS supports the following identification:
Absolute address-gives the absolute path of the JS file.
Such as:
Copy Code code as follows:
Require ("http://example/js/a");
On behalf of loading http://example/js/a.js.
Relative address--find the module with relative calls to the corresponding address of the JS file where the function is loaded.
For example, loading in the Http://example/js/b.js
Copy Code code as follows:
is loaded into the http://example/js/c.js.
Base Address--if the load string identity is neither an absolute path nor a "./" Start, then the relative seajs of "base" in the global configuration is addressed in a later manner.
Note that the above module is loaded without passing the suffix ". js", SEAJS will automatically add ". js". However, the following three scenarios are not added:
When you load CSS, such as:
Copy Code code as follows:
Require ("./module1-style.css");
The path contains the "?" , such as:
Copy Code code as follows:
Require (<a href= "Http://example/js/a.json?cb=func" >http://example/js/a.json?cb=func</a>);
When the path ends with "#", such as:
Copy Code code as follows:
Require ("http://example/js/a.json#");
Depending on the scenario, SEAJS provides three APIs for loading modules, Seajs.use,require and Require.async respectively, described below.
Seajs.use
Seajs.use is mainly used for loading portal modules. The entry module is equivalent to the main function of the C program and the root of the entire module dependency tree. Above in the Tinyapp small example, init is the Portal module. Seajs.use usage is as follows:
Copy Code code as follows:
Single mode
Seajs.use ('. a ');
Callback mode
Seajs.use ('. A ', function (a) {
A.run ();
});
Multi-module mode
Seajs.use (['. a ', './b '], function (A, b) {
A.run ();
B.run ();
});
The general Seajs.use is only used in the page loading portal module, SEAJS will follow the entry module to resolve all dependent modules and load them. If there is only one entry module, you can omit seajs.use by adding the "Data-main" property to the script tag that introduces the Sea.js, for example, the index.html above Tinyapp can be changed to read as follows:
Copy Code code as follows:
<! DOCTYPE html>
<meta charset= "UTF-8" >
<title>TinyApp</title>
<body>
<p class= "Content" ></p>
<script src= "./sea.js" data-main= "./init" ></script>
</body>
This kind of writing will make HTML more concise.
Require
Require is the SEAJS main module loading method, which is typically loaded with require when other modules are needed in a module:
Copy Code code as follows:
var m = require ('/path/to/module/file ');
Here is a brief introduction to SEAJS's automatic loading mechanism. As mentioned above, the use of Seajs HTML as long as the inclusion of sea.js can be, then the other JS file is how to load in it? Seajs will first download the entry module, and then follow the entry module to use regular expression matching code all the require, and then according to the Require file path identification download the corresponding JS file, to download the JS file iteration for similar operations. The entire process resembles a graph traversal operation (because there may be a cross loop dependency so the entire dependent data structure is a graph rather than a tree).
Understanding the above, the following rules are well understood:
The path identifier passed to require must be literal and cannot be an expression, as the following method of using require is incorrect:
Copy Code code as follows:
Require (' module ' + ' 1 ');
Require (' Module '. toLowerCase ());
This will cause seajs not to be able to properly match the corresponding JS files below.
Require.async
Above said Seajs will be open in the HTML page through static analysis of a one-time record of all the required JS files, if you want a JS file in use to download, you can use Require.async:
Copy Code code as follows:
Require.async ('/path/to/module/file ', function (m) {
Code of Callback ...
});
This only in the use of this module, the corresponding JS file will be downloaded, but also to achieve the JavaScript code on-demand loading.
Global configuration for Seajs
SEAJS provides a Seajs.config method to set up a global configuration and receive a configuration object that represents a global configuration. The specific use of the following methods:
Copy Code code as follows:
Seajs.config ({
Base: ' path/to/jslib/',
Alias: {
' app ': ' path/to/app/'
},
CharSet: ' Utf-8 ',
timeout:20000,
Debug:false
});
Where base is the path of the base address when addressing the base address. For example, base is set to http://example.com/js/3-party/:
Copy Code code as follows:
var $ = require (' jquery ');
will be loaded into the http://example.com/js/3-party/jquery.js.
The alias can set an abbreviation for a longer common path.
CharSet represents the CharSet property of the script tag when downloading JS.
Timeout indicates the maximum length of the download file, in milliseconds.
Debug indicates whether the work is in debug mode.
Seajs how to use with existing JS library
To use an existing JS library, such as jquery and Seajs, you simply encapsulate an existing library based on SEAJS's module-definition rules. For example, here's how to encapsulate jquery:
Copy Code code as follows:
Define (function () {
{{{{= jquery original code started
/*!
* JQuery JavaScript Library v1.6.1
* http://jquery.com/
*
* Copyright, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* Http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright, the Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date:thu May 12 15:04:36 2011-0400
*/
//...
}}}jquery Original Code End
return $.noconflict ();
});
Packaged deployment of SEAJS projects
SEAJS originally integrated a packaged deployment tool SPM, and later the author, in order to be more kiss, removed the SPM Seajs and became a separate project. The core idea of SPM is to merge all the code of the module into the entrance module, and because of the characteristic of SEAJS itself, the HTML can easily switch between the development environment and the production environment. However, because the SPM does not release the official version, so this article is not intended to be introduced in detail, interested friends can refer to its GitHub Project homepage https://github.com/seajs/spm/.
In fact, because each project uses the JS merge and compression tools are different, so SPM may not be entirely suitable for each project. After understanding the principle of seajs, you can write a merge package script that conforms to your own project characteristics.