我苦苦思索了几天才弄明白,但今天我终于需要你的帮助。
我的 repo :https://github.com/seoyoochan/bitsnut-web
我想要实现的目标:
- 加载和优化 r.js
- 为 RequireJS 和 r.js 编写 bower 任务:
任务是:RequireJS 的缩小、丑化和连接,并在生产环境中使用 r.js 进行优化
- 如何在使用wiredep
任务时排除index.html
中的js 脚本标签并通过RequireJS 加载器加载它们?
我使用 Yeoman“Webapp”生成器并生成了脚手架应用程序。
我通过 bower install
安装了主干、木偶、文本、下划线等
我通过删除 dependencies
修改了 bower.json
并且只在 dependencies
上留下了 "requirejs": "~2.1.16"
>。 (devDependencies
为空)
因为我使用 [2][grunt-wiredep]
,所有内容都会自动加载 bower_components
到 index.html
中。
我修改了 .bowerrc
以将依赖项存储在 app/scripts/vendor
中。
但是,问题是我不知道如何通过 ReuqireJS 成功加载它们,而不是将 vendor 作为脚本标签加载到 index.html
中。
我必须为 RequireJS 和 r.js 编写一些任务,但不知道如何实现这个目标(虽然我安装了 grunt-contrib-requirejs
)
我想按照第 4 种方法在 https://github.com/jrburke/requirejs/wiki/Patterns-for-separating-config-from-the-main-module 使用 r.js
.但我遇到的问题是 RequireJS 的文档确实建议不要使用 named module
,而是使用 anonymous module
。
我想听听关于我应该如何处理的各种意见。
非常感谢您的提前帮助!
最佳答案
您手动加载脚本 here和 here ,使整个 requireJS
变得无用。您还首先加载 main
here config.js#L49 .
相反,您应该只在 index.html 中包含这一行
<script data-main="scripts/config" src="scripts/vendor/requirejs/require.js"></script>
然后使用 define()
和 require()
加载该文件中的所有依赖项(就像您对 main
所做的那样)。由于您设置了 exports
,它将值设置为全局值,因此函数可以为空。这是一个示例:
define([
"jquery",
"underscore",
"backbone",
"marionette",
"modernizr"
], function () {
require([
"backbone.babysitter",
"backbone.wreqr",
"text",
"semantic"
], function () {
/* plugins ready */
});
define(["main"], function (App) {
App.start();
});
});
此外,baseUrl
与您的 data-main
属性文件夹 ( http://requirejs.org/docs/api.html#jsfiles) 的目录相同:
RequireJS loads all code relative to a baseUrl. The baseUrl is normally set to the same directory as the script used in a data-main attribute for the top level script to load for a page. The data-main attribute is a special attribute that require.js will check to start script loading.
所以我认为您在 config.js
中的 baseUrl
指向不存在的 scripts/scripts/
文件夹。它可以/应该是 vendor/
(并从所有声明中删除 vendor 部分)或留空。
代替 wiredep
,您可以尝试使用 https://github.com/yeoman/grunt-bower-requirejs它与 wiredep
做类似的事情,但专门用于 bower/requirejs
应用程序(参见:https://github.com/stephenplusplus/grunt-wiredep/issues/7)
您的存储库不包含 jQuery
的 dist 文件夹,但这里有一个 config.js
的工作示例:http://jsfiddle.net/petetnt/z6Levh6r/
至于module-definition,应该是
require(["dependency1", "dependency2"])
模块应该返回自己。当前,您的 main
文件将自己设置为依赖项
require(["main", "backbone", "marionette"], function(App, Backbone, Marionette){
由于您已经将 backbone
和 marionette
设置为具有 exports
的全局变量,您可以再次将函数属性设置为空,因此您的主文件应该是这样的:
require(["backbone", "marionette"], function(){
"use strict";
var App = new Backbone.Marionette.Application();
App.addInitializer(function(){
console.log("hello world!");
Backbone.history.start();
});
return App;
});
因为您已经使用define
来加载main
,所以不要再次require
。只需在 define
函数中调用 App.start()
即可。
https://jsfiddle.net/66brptd2/ (配置.js)
关于javascript - 'define' is not defined error on RequireJS & Webapp Yo generator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29314643/