How requirejs load commonjs packages?
我遵循http://requirejs.org/docs/api.html#packages来学习RequireJ如何加载CommonJS模块,但我无法获得它。
我有以下文件。
foo / foo.js
main.js
require.js
foo / foo.js,内容:
1 2 | exports.bar = '1234'; exports.xyz = function noop() {}; |
main.js:
1 2 3 4 5 6 7 | requirejs.config({ packages: [{name:'foo', main: 'foo'}] }); require(['foo'], function(foo) { console.log(foo.bar); }); |
表示无法读取未定义的栏
您已经错过了在问题中链接到的文档的重要部分:
While the packages can have the CommonJS directory layout, the modules themselves should be in a module format that RequireJS can understand. Exception to the rule: if you are using the r.js Node adapter, the modules can be in the traditional CommonJS module format. You can use the CommonJS converter tool if you need to convert traditional CommonJS modules into the async module format that RequireJS uses.
(已添加重点。)
这不是RequireJS可以理解的:
1 2 | exports.bar = '1234'; exports.xyz = function noop() {}; |
必须为:
1 2 3 4 | define(function(require, exports, module) { exports.bar = '1234'; exports.xyz = function noop() {}; }); |
您可以手动进行此转换,也可以使用