我关注http://requirejs.org/docs/api.html#packages了解 RequireJs 如何加载 CommonJS 模块,但我无法理解。
我有以下文件。
foo/foo.js main.js 需要.js
foo/foo.js 内容:
exports.bar = '1234';
exports.xyz = function noop() {};
main.js:
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 理解的东西:
exports.bar = '1234';
exports.xyz = function noop() {};
它必须是:
define(function(require, exports, module) {
exports.bar = '1234';
exports.xyz = function noop() {};
});
您可以手动执行此转换,也可以使用 r.js -convert
为您进行转换。
关于javascript - requirejs如何加载commonjs包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21872232/