RequireJS - NodeJS



節點介面卡可與 Require 和 Node 搜尋路徑的實現一起使用。如果沒有 RequireJS 使用的模組配置,你無需更改即可使用基於現有 Node 的模組。你可以使用 npm 命令將節點包安裝到專案的“node_modules”目錄中。

Node 只會載入來自本地磁碟的模組,而諸如 map、packages、paths 等配置選項僅當 RequireJS 載入模組時才會應用。

安裝 Node

你可以使用以下命令安裝 Node 介面卡,它將安裝最新的發行檔案 −

npm install requirejs

你也可以透過以下方式安裝 Node −

  • 你可以從 此連結下載 r.js 並將它保留在你的專案資料夾中。

  • r.js 儲存庫 獲取原始碼或透過 node dist.js 安裝它。

使用 Node

要使用節點,你需要擁有 require('requirejs') 並將 require 函式在配置中移至頂層的 main.js 檔案。

例如 −

var requirejs = require('requirejs');

requirejs.config({
   //load the mode modules to top level JS file 
   //by passing the top level main.js require function to requirejs
   nodeRequire: require
});

requirejs(['name1', 'name2'],
   function (name1, name2) {
      //by using requirejs config, name1 and name2 are loaded
      //node's require loads the module, if they did not find these
   }
);

使用 AMD 或 RequireJS 構建節點模組

你可以讓程式碼模組與 RequireJS 和 Node 配合工作,而不需要庫的使用者,然後使用 amdefine 包來完成此工作。

例如 −

if (typeof define !== 'function') {
   var define = require('amdefine')(module);
}

define(function(require) {
   var myval = require('dependency');

   //The returned value from the function can be used 
   //as module which is visible to Node.
   return function () {};
});

最佳化器作為 Node 模組

Node 模組使用 RequireJS 最佳化器作為一種 optimize 方法,透過使用函式呼叫而不是命令列工具。

例如 −

var requirejs = require('requirejs');

var config = {
   baseUrl: '../directory/scripts',
   name: 'main',
   out: '../build/main-built.js'
};

requirejs.optimize(config, function (buildResponse) {

   //The text output of the modules specify by using buildResponse 
   //and loads the built file for the contents
   //get the optimized file contents by using config.out 
   var contents = fs.readFileSync(config.out, 'utf8');
}, function(err) {
   //code for optimization err callback
});
廣告
© . All rights reserved.