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