RequireJS-NodeJS
Node 适配器可以与 Require 和 Node 的搜索路径的实现一起使用。如果 RequireJS 没有使用模块配置,您可以使用现有的基于 Node 的模块,而无需更改它们。您可以使用npm命令将节点包安装到项目的node_modules目录中。
Node 只会从本地磁盘加载模块,并且只有在 RequireJS 加载模块时才会应用配置选项,例如地图、包、路径等。
安装节点
您可以使用以下命令安装节点适配器,该命令将安装最新版本文件 -
npm install requirejs
您也可以通过以下方式安装节点 -
节点的使用
要使用该节点,您需要有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 模块使用 RequireJS 优化器作为优化方法,通过使用函数调用而不是使用命令行工具。
例如 -
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
});