RequireJS模块扩展另一个模块

时间:2014-09-05 12:35:13

标签: requirejs amd

我使用的项目有两个不同的文件包含在AMD中,另一个扩展另一个,项目是jsondiffpatch

该项目有两个文件(build/bundle.jsbuild/formatters.js),每个文件都导出jsondiffpatch。当我将它们包含在我的文件中时:

define(['jsondiffpatch',
        'jsondiffpatch-formatters'], function (jsondiffpatch) {
});

格式化程序扩展名不存在。如果我更改主配置make jsondiffpath取决于格式化程序,如:

shim: {
    'jsondiffpatch': {
        deps: ['jsondiffpatch-formatters']
    }
}

我仍然没有得到格式化程序。这是一种非常普遍的做法,但没有看到克服它;我知道它简单,我缺少什么?

2 个答案:

答案 0 :(得分:2)

这应该有效:

shim: {
    'jsondiffpatch-formatters': {
        deps: ['jsondiffpatch'],
        exports: 'jsondiffpatch.formatters'
    },
    'jsondiffpatch': {
        exports: 'jsondiffpatch'
    }
}

答案 1 :(得分:1)

当您使用像RequireJS这样的AMD加载程序加载jsondiffpatch时,格式化程序是不同的模块。换句话说,它与你加载没有AMD-loader的jsondiffpatch时的工作方式略有不同。这是一个完整的例子:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/xhtml; charset=utf-8"/>
    <link rel="stylesheet" href="bower_components/jsondiffpatch/src/formatters/html.css" type="text/css" />
    <link rel="stylesheet" href="bower_components/jsondiffpatch/src/formatters/annotated.css" type="text/css" />
    </head>
    <script type="text/javascript" src="bower_components/requirejs/require.js"></script>
  </head>
  <body>
    <div id="visual"></div>
    <hr/>
    <div id="annotated"></div>
    <script>
      require.config({
        baseUrl: ".",
        paths: {
          jsondiffpatch: "bower_components/jsondiffpatch/build/bundle",
          "jsondiffpatch.formatters": "bower_components/jsondiffpatch/build/formatters"
        },
        enforceDefine: true
      });
      require(["jsondiffpatch", "jsondiffpatch.formatters"],
        function (jsdp, formatters) {

        //
        // Code here adapted from jsondiffpatch's examples:
        // https://github.com/benjamine/jsondiffpatch
        //
        var left = { a: 3, b: 4 };
        var right = { a: 5, c: 9 };
        var delta = jsdp.diff(left, right);

        document.getElementById('visual').innerHTML =
          formatters.html.format(delta, left);
        document.getElementById('annotated').innerHTML =
          formatters.annotated.format(delta, left);
      });
    </script>
  </body>
</html>

除了上面的HTML,你唯一需要的是在Bower上安装RequireJS和jsondiffpatch。