5

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.

  1. Write normal Node-style module (module.exports.foo = ...)
  2. ...do something to build a UMD version of the module in a directory called /umd
  3. Add /umd to the files: [] property of package.json.
  4. Publish to npm
  5. 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)?

Steve Bennett
  • 114,604
  • 39
  • 168
  • 219
  • 1
    Possible duplicate of [How can I share code between Node.js and the browser?](https://stackoverflow.com/questions/3225251/how-can-i-share-code-between-node-js-and-the-browser) – Aurora0001 May 28 '17 at 19:22

0 Answers0