如何在nodejs和web上同时使用javascript?

我想在nodejs和web javascript中使用configuration文件。

config.js:

var conf = {}; conf.name = 'testname'; conf.pass = 'abc123'; conf.ip = '0.0.0.0'; conf.port = 100; conf.delay = 5; exports.config = conf; 

在nodejs中使用它:

 var conf = require('config.js'); console.log(conf.config.name); 

想在html中使用这个相同的文件,但是如何? 我正在这样想,但我不知道如何在networking中使用它。 当我尝试在networking中使用它我得到参考错误:出口没有定义。

config.html:

 <!doctype html> <html lang="en"> <head> <title>Document</title> <script src="./config.js"></script> <script> var cnf = conf; function getCnf(){ alert(cnf.config.name); } </script> </head> <body> <button onclick="getCnf();">test</button> </body> </html> 

任何人都知道我必须改变config.js在系统nodejs和web中使用它?

PS:Webside运行在nodejs http npm模块上。

你可以把这个条件,像这样

 if (typeof module !== 'undefined' && module.exports) { module.exports.config = conf; } 

这可以确保在设置任何exports值之前, moduleexports都可用。

注意: exports只是引用module.exports另一个variables。 所以,他们都是一样的,除非你分配其他任何东西。 如果你给它们中的任何一个分配了某些东西, module.exports任何东西都将被导出到Node.js中。 您可以在此博客文章中阅读有关exports更多信息

谢谢,那种types就是我所需要的。

@Phoenix:我知道有办法做到这一点,但这不是必要的。 该variables仅用于稍后的一些ajax请求和deley定时器。

您可以使用browserify将您的CommonJS捆绑到浏览器,而不必使用环境开关。

  1. 使用npm i browserify -g安装npm i browserify -g
  2. 捆绑你的config.js并用-r标签将其导出供外部使用

    browserify -r ./config.js -o bundle.js

  3. 在你的代码中包含这个包并使用它:

 <!doctype html> <html lang="en"> <head> <title>Document</title> <script src="./bundle.js"></script> <script> var cnf = require("./config.js"); function getCnf(){ alert(cnf.config.name); } </script> </head> <body> <button onclick="getCnf();">test</button> </body> </html>