6

我正在编写一个需要 jQuery UI 和 jQuery Mobile 的 Node JS 应用程序。我正在使用 Browserify 将模块打包在一个 js 文件中。

我有以下代码在我的项目中包含 jQuery 和 jQuery UI。

var jQuery = require('jquery');
require('jquery-ui-browserify'); 

它有效。当我尝试添加 jQuery mobile 时出现问题,或者需要:

require('./lib/jquery.mobile-1.4.0.min.js');

或带有脚本标签

<script src="/lib/jquery.mobile-1.4.0.min.js" type="text/javascript"></script>

我犯了同样的错误:

“未捕获的类型错误:无法设置未定义的属性‘移动’”。

我知道我收到此错误是因为 jQuery mobile 在 Window 中查找 jQuery 对象但没有找到它,但如何修复它?npm 上没有 jQuery 移动模块。

4

4 回答 4

4

这是一个使用browserify-shim和 jquery + jquery mobile 的简单可运行演示: https ://gist.github.com/mchelen/a8c5649da6bb50816f7e

最重要的几行是:

package.json

 "browserify-shim": {
   "jquery": "$",
   "jquery-mobile" : { "exports": "$.mobile", "depends": [ "jquery:$" ] }
 }, 

entry.js

var $ = require('jquery');
$.mobile = require('jquery-mobile'); 
于 2014-11-24T23:17:35.197 回答
1

您需要指定 jquery-mobile 的路径。

在 package.json

"devDependencies": {
    "gulp": "3.8.7",
    "browserify": "9.0.3",
    "browserify-shim": "3.8.3",
    // [...] many more hidden
    "jquery": "1.11.0",
    "jquery-mobile": "1.4.1"
},
"browser": {
    "jquery-mobile": "./node_modules/jquery-mobile/dist/jquery.mobile.js"
},
"browserify": {
    "transform": [ "browserify-shim" ]
},
"browserify-shim": {
    "jquery": "$",
    "jquery-mobile" : { "exports": "$.mobile", "depends": [ "jquery:$" ] },
    "three": "global:THREE"
}

在你的 js 文件中:

var $ = require('jquery');
$.mobile = require('jquery-mobile');

你可以在这里看到更多

我也在使用 gulp。在 gulpfile.js 中:

gulp.task('browserify', ['jshint'], function () {
    return browserify('./src/js/app.js')
    .bundle()
    .pipe(source('myjs.js'))
    .pipe(gulp.dest('./js/'));
});
于 2015-03-20T12:41:23.320 回答
1

您必须使用 browserify 垫片。

您可以使用 grunt-browserify 在页面加载之前运行您的需求。

然后,您可以简单地使用 shim 导出“$”并在 JQuery.mobile 中要求 jQuery,就像这里使用另一个插件完成的一样:

用 browserify 填充一个 jQuery 插件

如果您不喜欢 grunt 方法,也可以使用https://github.com/thlorenz/browserify-shim

于 2014-03-19T13:32:46.260 回答
0

我有同样的问题。

现在我正在对除 jquery 和 jquery-mobile 之外的所有内容使用 browerify,并且我将 jquery 和 jquery-mobile 的脚本标签添加到标题中,并在正文底部添加了捆绑包的脚本标签(所以,需要(“.. /jquery") 和 require("../jquery-mobile") 不再需要)。糟糕的解决方案,但它有效

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <link href="js/vendors/jquery.mobile-1.4.0.min.css" rel="stylesheet">
  <script src="js/vendors/jquery-1.10.2.min.js"></script>
  <script src="js/vendors/jquery.mobile-1.4.0.min.js"></script>
</head>

<body>
  <div class="Application">
  </div>
  <script src="js/app.built.js"></script>
</body>
</html>
于 2014-02-18T07:30:33.637 回答