JavaScript Module (1)— Require.JS (AMD loader)

Before reading the article, follows I wrote is not to discuses about lots of details on Require.js. The main purpose of follows is to list some code snippets or syntax in common use.

本篇工具需求: 請下載RequireJS,而 Node.js、npm可不需安裝。

RequireJS is one of the more well known (and thus ‘popular’) AMD script loaders.

What is AMD?
AMD stands for “Asynchronous Module Definition” and is a proposed API for loading modules (i.e. scripts) asynchronously.

RequireJS 2.0

Notes:

  1. RequireJS 既然是模組化loader,那在寫模組的時候要按在他個規定去寫,例如jQuery1.7.2版本已上就納入AMD支援。
    define(‘jquery’, [], function() { … });
  2. RequireJS 為了方便也可以載入 非模組化的js檔案。這時要使用 shim-config http://requirejs.org/docs/api.html#config-shim

本篇必要檔案:

The files for require.js exmaple

Ex1 : Shim or not Shim ?

index.html

data-main=”main” 指定main.js當作主要Module檔案入口

main.js

myModule1 : 對應到myModule1.js檔案,是按照AMD規範寫的Module。

myModule2 : 對應到myModule2.js檔案,是按照AMD規範寫的Module,例如CommonJS。此時要寫Shim-config才可以export function,否則只是global function。

exports: ‘myMath2’ 中的 myMath2 就是我們在myModule2.js定義中的myMath2函式,當我們使用 function myMath2(){…} 的方式定義一個函示時候,它就是全域函式。如果我們把它export給requirejs,那當我們的code依賴於myModule2 Module時,就可以拿到myMath2的函式使用了。

myModule1.js (Standard AMD Define)
myModule2.js (No any module define)

若是您有多的function要export,也可以改用init 設定。

main.js

How does it work?

  1. RequireJS reads the dependency array.
  2. Then it checks if each module was already registered for the current context.
  3. Resolve the ID into a URI by checking the paths.config and current module path.
  4. After all the dependencies are ready it calls the definition function passing the dependencies as arguments, it will then register the module as the value returned by the definition function.

如想下載本篇範例檔請留言。

Reference:

Like what you read? Give Alpha Orange a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.