【问题标题】:RequireJS OptimizationRequireJS 优化
【发布时间】:2013-11-29 00:40:29
【问题描述】:

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

问题是,当我在优化后设置对输出 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 文件中?也许我需要在配置中添加其他内容?或者问题不在于配置?

谢谢, 奥利

【问题讨论】:

  • 你也加入了require.js吗?您必须单独导入它。

标签: javascript optimization requirejs amd grunt-contrib-requirejs


【解决方案1】:

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

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

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

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

【讨论】:

  • 太好了,它有效!我无法理解 requireJS 团队为什么没有想到将这些信息放在他们的“优化”教程中......
【解决方案2】:

如果您使用 RequireJS 模块化了您的项目,则必须包含 require.js

<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 {};
}));

【讨论】:

    【解决方案3】:

    试试:

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

    【讨论】:

      猜你喜欢
      • 2016-02-17
      • 2017-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多