How to use UMD in a browser without any additional dependencies

Suppose I have a UMD module like this (stored in 'js / mymodule.js'):

(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.mymodule = global.mymodule || {}))); }(this, function (exports) { 'use strict'; function myFunction() { console.log('hello world'); } })); 

How can I use this module in an HTML file like this? (without requirejs, commonjs, systemjs, etc.)

 <!doctype html> <html> <head> <title>Using MyModule</title> <script src="js/mymodule.js"></script> </head> <body> <script> /* HOW TO USE myFunction from mymodule.js ??? */ </script> </body> </html> 

Thanks so much for any help.

+7
javascript html requirejs commonjs systemjs
source share
3 answers

So, you are working in an environment without RequireJS, CommonJS, SystemJS, etc.

The factory((global.mymodule = global.mymodule || {})) key factory((global.mymodule = global.mymodule || {})) does a few things:

  • If global.mymodule true, then it is equivalent

     global.mymodule = global.mymodule // A noop. factory(global.mymodule) 
  • Otherwise, this is equivalent to:

     global.mymodule = {} factory(global.mymodule) 

Inside the factory : your factory, you should export what you want to export from your module by assigning exports . So you export myFunction by doing exports.myFunction = myFunction .

Outside the factory : external values ​​are exported to mymodule , which has been exported to global space. If you want to use myFunction , for example, you do mymodule.myFunction(...) .

If it is not clear. factory in your code is a function starting with function (exports) { where you correctly placed myFunction .

+10
source share

The simple answer: if you use regular UMD, it should be available in window.mymodule (or any other lib name).

+2
source share

The format of the amd module is for asynchronous loading, so you cannot directly reference the file in the script tag. If this is used for development, you can use a loader like requirejs (see this link for amd specs). If you use this in production mode, then several alternatives:

1) Use requirejs, but start the optimization process that will link the amd file 2) Use another miniaturization process, for example, a web package or build it into your interface (grunt, gulp, etc.).

I am afraid in terms of downloading the file directly, this is not possible, due to the nature of amd (the ability to declare dependencies on other modules).

Hope this helps.

-2
source share

All Articles