首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RequireJS优化

RequireJS优化
EN

Stack Overflow用户
提问于 2013-11-15 15:09:11
回答 3查看 1.1K关注 0票数 1

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

问题是,当我在优化后设置对输出javascript文件的引用时,我在浏览器中得到以下错误:

未定义的ReferenceError: defined未定义主-built.js:14735

看起来,我所有的应用程序模块都存在,但RequireJs却不见了。

这是我的build.json配置文件:

代码语言:javascript
复制
{
  "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"]
}

如何向输出js文件中添加必需js?也许我需要在配置中添加其他内容?或者问题不在于配置?

谢谢你,奥利

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-11-15 15:18:42

尝试:

代码语言:javascript
复制
<script src="scripts/require.js" data-main="scripts/main-built"></script>
票数 1
EN

Stack Overflow用户

发布于 2013-11-15 15:14:23

如果我的理解是正确的,这就是它的工作方式。

r.js所做的就是将所有RequireJS模块编译成一个文件。但是,您仍然需要使用RequireJS脚本加载该文件,例如:

代码语言:javascript
复制
<script data-main="scripts/main" src="scripts/require.js"></script>

因此,只需添加一个缩小版本的require.js到您的网站,并加载优化模块使用。

票数 1
EN

Stack Overflow用户

发布于 2013-11-15 15:14:35

如果您已经使用require.js模块化了项目,则必须包括RequireJS:

代码语言:javascript
复制
<script data-main="scripts/main" src="scripts/require.js"></script>

这是因为RequireJS处理模块的加载和解决依赖关系。没有它,浏览器就不知道define是什么意思。解决这个问题的一种方法是使用UMD (通用模块定义)。这使得您的模块可以与RequireJS一起使用,也可以不使用它。您可以看到许多例子,这里。一个适合您的用例是:

代码语言:javascript
复制
// 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 {};
}));
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20004161

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档