1

我正在使用r.js优化我的应用, 正如我在几个示例中看到的,我使用build.json配置文件来配置我的优化选项。RequireJS优化

的问题是,当我设置参考输出优化后我真的收到以下错误在浏览器中的JavaScript文件:

Uncaught ReferenceError: define is not defined main-built.js:14735

的样子,我的所有应用模块都存在,但RequireJs缺失。

这是我build.json配置文件:

{ 
    "baseUrl": "../", 
    "name": "src/modules/main", 
    "include": ["src/modules/main", "src/modules/navbar/navbar", "src/modules/contact/contact", "src/modules/about/about"], 
    "exclude": [], "optimize": "none", "out": "main-built.js", 
    "insertRequire": ["src/modules/main"] 
} 

如何添加requirejs到输出js文件?也许我需要添加其他配置?或者问题可能不是配置?

感谢, 大利

+1

有你'包含如require.js'好?你将不得不分别导入它。 –

回答

1

尝试:

<script src="scripts/require.js" data-main="scripts/main-built"></script> 
1

如果我理解正确的,这是它应该如何工作。

r.js做的是将所有RequireJS模块编译成单个文件。但是你仍然需要加载与RequireJS脚本文件,例如:

<script data-main="scripts/main" src="scripts/require.js"></script> 

所以只需添加require.js的缩小版本到你的网站,并使用加载优化模块。

+0

太棒了,它的工作原理!我无法理解requireJS团队如何没有想到将这些信息放入他们的“优化”教程中。 –

1

你必须包括require.js如果你有你的模块化用项目RequireJS:

<script data-main="scripts/main" src="scripts/require.js"></script> 

这是因为RequireJS处理模块和解析相关的加载。没有它,你的浏览器不知道define的含义。解决这个问题的方法是使用UMD(通用模块定义)。这使得您的模块可以使用或不使用RequireJS。你可以看到很多例子here。一个适合您的使用情况是:

// Uses AMD or browser globals to create a module. 

// If you want something that will also work in Node, see returnExports.js 
// If you want to support other stricter CommonJS environments, 
// or if you need to create a circular dependency, see commonJsStrict.js 

// Defines a module "amdWeb" that depends another module called "b". 
// Note that the name of the module is implied by the file name. It is best 
// if the file name and the exported global have matching names. 

// If the 'b' module also uses this type of boilerplate, then 
// in the browser, it will create a global .b that is used below. 

// If you do not want to support the browser global path, then you 
// can remove the `root` use and the passing `this` as the first arg to 
// the top function. 

(function (root, factory) { 
    if (typeof define === 'function' && define.amd) { 
     // AMD. Register as an anonymous module. 
     define(['b'], factory); 
    } else { 
     // Browser globals 
     root.amdWeb = factory(root.b); 
    } 
}(this, function (b) { 
    //use b in some fashion. 

    // Just return a value to define the module export. 
    // This example returns an object, but the module 
    // can return a function as the exported value. 
    return {}; 
}));