[英]Including JQuery Mobile in a Node JS project with Browserify
我正在編寫一個Node JS應用程序,我需要jQuery UI和jQuery Mobile。 我正在使用Browserify將模塊打包到一個js文件中。
我有以下代碼在我的項目中包含jQuery和jQuery UI。
var jQuery = require('jquery');
require('jquery-ui-browserify');
它有效。 當我嘗試使用require添加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>
我犯了同樣的錯誤:
“未捕獲的TypeError:無法設置未定義的屬性'mobile'”。
我明白我得到這個錯誤,因為jQuery mobile在Window中查找jQuery對象並且找不到它,但是如何修復它? npm上沒有jQuery移動模塊。
這是一個使用browserify-shim和jquery + jquery mobile的簡單runnable演示: 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');
您必須使用browserify墊片。
您可以使用grunt-browserify在頁面加載之前運行您的需求。
然后你可以簡單地使用一個墊片導出'$'並在JQuery.mobile中需要jQuery,就像在這里使用另一個插件一樣:
如果你不喜歡grunt方法,也可以使用https://github.com/thlorenz/browserify-shim
您需要指定jquery-mobile的路徑。
在packadge.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/'));
});
我有同樣的問題。
現在我正在使用除了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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.