I want to write a single Javascript module that can be used both through NPM/Browserify:
let mymodule=require('mymodule');
mymodule.foo()
and alternatively by linking to a hosted version without building:
<script src="...../mymodule.js"></script>
<script>
mymodule.foo()
</script>
Obviously I'm expecting the two versions of the code to be different, but I'd like to be able to build one automatically from the other (or both from the same source).
I understand that UMD (Universal Module Definition) is part of a solution, as is unpkg.com, but I don't quite understand how to put it together.
- Write normal Node-style module (
module.exports.foo = ...
) - ...do something to build a UMD version of the module in a directory called
/umd
- Add
/umd
to thefiles: []
property ofpackage.json
. - Publish to npm
- Now it's on unpkg.com
If that's correct, what is step 2? I'm not currently using any build tool as this module is very simple.
And if accessing it in the browser, what variable name will the module be accessed through (mymodule
in my example above)?