jquery 出现在 browserify bundle.js 但在浏览器中不起作用

jquery appears in browserify bundle.js but not working in browser

我正在学习这个关于 Browserify 入门的简短教程 Getting Started with Browserify。 尽管完全遵循所有内容 jquery 在捆绑时无法在页面上工作,即。下面我的 app.js 代码中的按钮元素没有附加到正文中。使用 chrome 开发工具检查了所有我能想到的东西,以确保所有加载正常,它 is.The bundle.js 加载正常,我的 jquery 代码来自 app.js 在里面。 alert() 和 console.log() 输出也很好,所以我知道 jQuery 被特别忽略了。尝试将 jquery 版本更改为教程的版本,但仍然无效。我知道 jQuery 代码本身没问题,因为当我将代码直接添加到索引页上并将 link 直接添加到 node_modules 目录中的 jquery.js 时,它会起作用。任何想法可能是什么问题?提前致谢!

app.js

var $ = require('jquery')
alert("hi from app.js") // this appears in browser on page load

// none of this jQuery currently works using Browserify
var button = $('<button/>').html('click me').on('click', function() {
alert("hi from browserify!")
})
$('body').append(button)

console.log("where is jQuery code ....."); // this logs in dev console

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Browserify Test with jQuery</title>
    <script src="bundle.js" charset="UTF-8"></script>
<!--<script src="node_modules/jquery/dist/jquery.js"></script>-->
  </head>
  <body>
  <!--<script>
    var button = $("<button/>").html("click me").on("click", function() {
    alert("hi from browserify!")
    })
   $("body").append(button)
  </script>-->
</body>
</html>

这是出现在 Browserify 创建的 bundle.js 文件中的代码。

......// rest of bundle.js 
},{}],2:[function(require,module,exports){
var $ = require('jquery')
alert("hi from app.js")

var button = $('<button/>').html('click me').on('click', function() {
alert("hi from browserify!")
})
$('body').append(button)

console.log("where is jQuery code .....");

},{"jquery":1}]},{},[2]);

package.js

{
"name": "browserify-test",
"version": "1.0.0",
"description": "Testing Browserify",
"main": "index.js",
"scripts": {
  "build": "browserify app.js -o bundle.js",
  "watch": "watchify app.js -o bundle.js"
},
"author": "MikeM",
"license": "ISC",
"devDependencies": {
"browserify": "^10.2.3",
"jshint": "^2.8.0",
"watchify": "^3.2.1"
},
"dependencies": {
  "jquery": "^2.1.4"
}
}

尝试将 var $ = require('jquery') 更改为 global.jQuery = require('jquery')。这会将其附加到全局对象,即浏览器中的 window。

我遇到了同样的问题。当 DOM 还没有准备好时,发现我在 head 中加载了 bundle.js。尝试将代码包装在 $(function(){...//code here...}) 或将 bundle.js 移动到 body.

的末尾

我建议对更改进行通用综合: 尝试改变:

window.jQuery = require('jquery');
window.$ = global.jQuery;