javascript - requirejs如何加载commonjs包?

标签 javascript requirejs single-page-application

我关注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/

相关文章:

javascript - jQuery 切换动态生成的嵌套元素

javascript - 如何在 TypeScript 中新建一个类

angular - SPA Angular index.html 未更新缓存(我使用缓存破坏)

javascript - 在 Knockout 中过滤 observableArray

javascript - 使用 CSS 更新 <select> 颜色,取决于选择的选项

javascript - 在加载@font-face-font 之前如何等待第一次 Canvas 重绘?

javascript - 定义模块并立即使用 RequireJS

javascript - 自定义提供程序 $injector :modulerr 的 Angular 依赖注入(inject)

javascript - 在 Angular 中,创建不带 # 链接且不修改服务器的 spa

javascript - 为 "single-page"webapp 禁用惯性滚动