【问题标题】:Browserify with nodejs is not working使用 nodejs 的 Browserify 不起作用
【发布时间】:2015-12-26 03:17:44
【问题描述】:

我正在创建一个示例应用程序来学习如何在客户端使用 nodejs。在运行这个练习之前,我已经安装了:node、npm 和 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"
    }];

并且正在使用 browerify 生成 application.js

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

问题:

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

我错过了什么吗?或以错误的方式做某事。

【问题讨论】:

  • require 在 JS 中的工作方式与在 PHP 中的 require 不同;你应该从一个模块中导出一些东西。将module.exports = json; 放入您的data.js 文件中,然后重试。

标签: node.js browserify


【解决方案1】:

您没有从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 functionfunction (require, module, exports) 签名。这就是为什么您可能没有全局变量的原因。如果需要,请使用global.window.

【讨论】:

  • 啊……我怎么错过了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-05
  • 1970-01-01
相关资源
最近更新 更多