[英]Node.JS newbie: how to export functions and use them in browserify modules?
Suppose I have this simple.js
file:假设我有这个
simple.js
文件:
function Square(x)
{
return x * x;
}
function Cube(x)
{
return x * x * x;
}
Note that this code doesn't actually do anything by itself, it just defines these two simple functions.请注意,这段代码本身实际上并没有做任何事情,它只是定义了这两个简单的函数。
Now I want to browserify
this file, so I get a.js file that I can include in a regular HTML file, and then use the Square
and Cube
functions in there.现在我想浏览这个文件,所以我得到一个 .js 文件,我可以将其包含在常规
browserify
文件中,然后在其中使用Square
和Cube
函数。
My problem is I don't understand how module.exports
or exports
works, or what exactly it is supposed to represent or contain.我的问题是我不明白
module.exports
或exports
是如何工作的,或者它到底应该代表或包含什么。
My goal is to be able to do this in a example.html
file:我的目标是能够在
example.html
文件中执行此操作:
<!DOCTYPE html><html><head><meta charset='utf-8'>
<script src='myfunctions.js'></script>
<script>
var x = Square(3);
var y = Cube(5);
</script>
</head><body></body></html>
But if I do但如果我这样做
browserify simple.js > myfunctions.js
then the above script obviously doesn't work, the Square
and Cube
functions are not defined.那么上面的脚本显然是不行的,
Square
和Cube
函数没有定义。
I understand I have to somehow export those functions, but I don't know how, and I also don't know how to address them from within the HTML script.我知道我必须以某种方式导出这些函数,但我不知道如何导出,而且我也不知道如何从 HTML 脚本中解决它们。
I'm guessing I have to do something like this:我猜我必须做这样的事情:
<!DOCTYPE html><html><head><meta charset='utf-8'>
<script src='myfunctions.js'></script>
<script>
const myFuncs = ...???... // not sure what this should be?!
var x = myFuncs.Square(3);
var y = myFuncs.Cube(5);
</script>
</head><body></body></html>
I also experimented with using --s SomeSymbolName
in the browserify
line, but I couldn't get it to work.我还尝试在
browserify
行中使用--s SomeSymbolName
,但我无法让它工作。
What's the right approach for this?正确的方法是什么?
Found it after some more messing around, I add this line to simple.js
:经过一番折腾后找到了它,我将这一行添加到
simple.js
中:
module.exports = { 'Square':Square, 'Cube':Cube };
Then I use browserify
with a standalone symbol like this:然后我将
browserify
与这样的独立符号一起使用:
browserify simple.js --standalone myFuncs > myfunctions.js
And now I can include myfunctions.js
in the HTML file, and use the functions from within JavaScript like this:现在我可以将 myfunctions.js 包含在
myfunctions.js
文件中,并像这样使用 JavaScript 中的函数:
var x = myFuncs.Square(3);
var y = myFuncs.Cube(5);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.