[英]Common module in node.js and browser javascript
我正在开发一个 node.js 应用程序,我想在客户端使用我为 node.js 服务器创建的模块。
一个示例模块是 circle.js:
var PI = Math.PI;
exports.area = function (r) {
return PI * r * r;
};
exports.circumference = function (r) {
return 2 * PI * r;
};
你做一个简单的
var circle = require('./circle')
在节点中使用它。
我怎么能在我的客户端 javascript 的 web 目录中使用相同的文件?
这似乎是如何制作一个可以在客户端使用的模块。
https://caolan.org/posts/writing_for_node_and_the_browser.html
我的模块.js:
(function(exports){
// your code goes here
exports.test = function(){
return 'hello world'
};
})(typeof exports === 'undefined'? this['mymodule']={}: exports);
然后在客户端使用模块:
<script src="mymodule.js"></script>
<script>
alert(mymodule.test());
</script>
此代码将在节点中工作:
var mymodule = require('./mymodule');
Webmake用于将 CommonJS/NodeJS 模块移植到浏览器。 试试看
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.