简体   繁体   English

Node.JS 新手:如何导出函数并在 browserify 模块中使用它们?

[英]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文件中,然后在其中使用SquareCube函数。

My problem is I don't understand how module.exports or exports works, or what exactly it is supposed to represent or contain.我的问题是我不明白module.exportsexports是如何工作的,或者它到底应该代表或包含什么。

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.那么上面的脚本显然是不行的, SquareCube函数没有定义。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM