Browserify 与 nodejs 不工作

Browserify with nodejs is not working

我正在创建一个示例应用程序来学习如何在客户端使用 nodejs。在 运行 这个练习之前我已经安装了 : node, npm with browserify;

目录结构

lesseon1
 - index.html
 - application.js
 - js
   - data.js
   - listdata.js

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Node Lesson 1</title>
    <script type="text/javascript" src="application.js"></script>
</head>
<body>
<div id="names"></div>
    <script type="text/javascript">
        var ol = document.createElement("ol");
        ol.innerHTML = window.list;
        document.getElementById("names").appendChild(ol);
    </script>
</body>
</html>

listdata.js

var jsonData = require("./data.js");

for(item in jsonData){
    console.log(jsonData[item].name);
    window.list += "<li>" + jsonData[item].name + "</li>";
}

console.log(window.list);

data.js

var json = [{
    "name" : "Rohit"
    },{
    "name" : "Amit"
    },{
    "name" : "Arti"
    }];

并且 application.js 正在使用 browerify

生成
~/node_modules/.bin/browserify -e js/listdata.js -o application.js

问题:

它也在浏览器和浏览器控制台中打印未定义。但是,如果我在 index.html 中复制粘贴 js 代码,一切正常。 在 listdata.js 中,有 2 个 console.log() 语句。但它只执行最后一个。

我错过了什么吗?或者做错事。

您没有从 data.js 导出。

var json = [{
    "name" : "Rohit"
    },{
    "name" : "Amit"
    },{
    "name" : "Arti"
    }];
module.exports = json;

或者您可以更改为 data.json,只需输入有效的 json,而不输入 varexports,然后在 listdata.js 中将其用作 var jsonData = require("./data.json");

每个 required 文件,browserify wraps into function 带有 function (require, module, exports) 签名。这就是为什么您可能没有全局变量的原因。如果需要,请使用 global.window..