Suppose I have this simple.js file:
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.
My problem is I don't understand how module.exports or exports works, or what exactly it is supposed to represent or contain.
My goal is to be able to do this in a example.html file:
<!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.
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.
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.
What's the right approach for this?
Found it after some more messing around, I add this line to simple.js :
module.exports = { 'Square':Square, 'Cube':Cube };
Then I use browserify with a standalone symbol like this:
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:
var x = myFuncs.Square(3);
var y = myFuncs.Cube(5);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With