简体   繁体   中英

How can I add UMD so I can use my module in the browser and as an NPM module?

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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