2

Okay, I've just gotten dropped into a project I have several different modules written in AMD format. I need to get these javascript files that are loosely related into one javascript file, that will then be referenced as yet another AMD module across different projects (probably from a CDN).

The problem I'm facing is when I run r.js against these files and get them into one file, when I pull that combined file into another project it just gets spit out as undefined.

To give an idea of what I'm talking about

words.spelling.js

define(['jquery', 'some.other.class'], function($, foo){
...
}

words.grammar.js

define(['jquery', 'some.other.class'], function($, foo){
...
}

words.translation.js

define(['jquery', 'some.other.class'], function($, foo){
...
}

Run through r.js into words.min.js

Then say I pull it into app.js as

require(['jquery', 'app/main/main', 'words.min'], function($, main, words) {
$(document).ready(function() {
    console.log(words);
}

words just shows up as undefined.

Just concatenating them all doesn't do anything as that just gives me a bunch of define statements one after another.

I tried creating a fake class that has

define(['word.grammar', 'word.translation', 'word.spelling'], function( g, t, s){
    return {
      grammar: g,
      translation: t,
      spelling: s
    };
});

and running that through r.js, but no dice there either. Am I missing something here or am I going to have re-write these in non-AMD format so I can concatenate them together and return one giant object? Keep in mind, words.min.js is going to have to be hosted on a CDN and cached as it'll be shared throughout a number of projects so I need that as a separate file.

4

1 回答 1

3

一种解决方案是使用路径配置将这些模块名称映射到它们的实际文件:

所以在开发中你使用这样的东西

require.config({
  paths: {
    'words.spelling': 'libs/words.spelling',
    'words.grammar': 'libs/words.grammar',
    'words.translation': 'libs/words.translation'
  }
}

您需要将相同的路径配置从开发传递到 r.js 优化器,以便它放在组合文件中的模块名称只有名称,而不是一些额外的路径信息。例如,您希望组合包中的模块名称为:'words.spelling',而不是'some/other/path/words.spelling'

然后要在另一个应用程序中使用组合版本,您可以执行以下操作将所有这些模块名称映射到同一个文件:

require.config({
  paths: {
    'words.spelling': 'libs/words.min',
    'words.grammar': 'libs/words.min',
    'words.translation': 'libs/words.min'
  }
}

部分困惑是这不是 r.js 优化器的主要用途。它似乎是为最终网站开发人员设计的,而不是模块开发人员使用的。但正如您在上面看到的,可以强制它进入该模式。

于 2013-06-12T22:40:29.903 回答