1

I'm trying to make my NPM module work in the browser, but I'm having a little trouble understanding the UMD syntax. Here are my requirements for my module, which I'll call Mod.

  • I need to be able to call child functions of Mod, like Mod.DoSomething(), Mod.Utils.DoSomethingElse(), etc. from other files in the browser
  • It needs to play nice with Webpack, Browserify, RequireJS, etc.
  • I need to be able to require it as a module in an NPM package, just like any other package. var mod = require('mod'); var returnedVal = Mod.DoSomething;

I don't have any dependencies, but I'd appreciate an example of how to do it both with and without dependencies. One of my main questions is how to export the child functions, so please include them in the example. Thanks!

Ben Gubler
  • 1,393
  • 3
  • 18
  • 32
  • This is an odd question for 2018: UMD isn't a popular format anymore, simply because AMD isn't popular anymore. Use either CommonJS (the vast majority of npm modules - which works in the browser via browserify) or ES6 modules (which also work in both, and is a good bet for the future, but has some limitations, eg can't export a single function). – mikemaccana May 15 '18 at 15:10

1 Answers1

1

I went through the same situation recently so even though it was an old question I would like to share my experience.

I use webpack and to make my npm module work in browser the solution I can find is to set webpack output setting libraryTarget: 'umd', check this article for details

But one mistake I made after reading that article was I misunderstand the relation between umd and es6 module, thought they were basically the same. Check my own question for details ES6 modules via script tag has the error "The requested module does not provide an export named 'default' "

About which module I should use in browser I would like to quote an answer here https://stackoverflow.com/a/55659242/301513

Today, the most likely answer is: use the UMD module. Some time in the future it may be: use ECMAScript modules; but we don't yet (2019) have consensus on how those will be distributed.

Qiulang
  • 10,295
  • 11
  • 80
  • 129