可以将Node适配器与Require和Node的搜索路径一起使用。如果RequireJS没有使用模块配置,则可以使用现有的基于Node的模块而无需更改它们。您可以使用npm命令将节点软件包安装在项目的node_modules目录中。
Node将仅从本地磁盘加载模块,并且仅当RequireJS加载模块时,才会应用配置选项(例如地图,程序包,路径等)。
安装节点
您可以使用以下命令来安装节点适配器,该命令将安装最新的发行文件-
npm install requirejs
您还可以通过以下方式安装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模块将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 });
作者:terry,如若转载,请注明出处:https://www.web176.com/requirejs/1985.html