Make my requirejs / amd javascript function friendly?

I created a javascript library that adds only one global object to the global space.

The global object is a function, and the function name matches the file name.

Here's what it looks like:

filename: myfunction.js

code:

myfunction = function() { ... }; 

How to make my library compatible with amd and require.js?

+4
source share
2 answers

Requirejs docs will tell you how to make an AMD compatible module. However, information on how to save a module that works when used without AMD (the <script> ) is difficult to find there. In any case, when the "define" method is defined in the context of Requrirejs. Otherwise, the example below simply uses window.x (not the most elegant solution) to pull a function into global space from a closure.

 (function (module) { if (typeof define === "function" && define.amd) { define(function () { return module; }); } else { window.myfunction = module.myfunction; } }({ myfunction: function () { /* ... */ } })); 

See also: fooobar.com/questions/147385 / ...

+9
source

I found a great post that explains the whole process.

http://ifandelse.com/its-not-hard-making-your-library-support-amd-and-commonjs/

In a nutshell, the author proposed the following template:

** Here postal.js is an AMD / Commonjs compatible module.

 (function (root, factory) { if(typeof define === "function" && define.amd) { // Now we're wrapping the factory and assigning the return // value to the root (window) and returning it as well to // the AMD loader. define(["postal"], function(postal){ return (root.myModule = factory(postal)); }); } else if(typeof module === "object" && module.exports) { // I've not encountered a need for this yet, since I haven't // run into a scenario where plain modules depend on CommonJS // *and* I happen to be loading in a CJS browser environment // but I'm including it for the sake of being thorough module.exports = (root.myModule = factory(require("postal"))); } else { //node.js diverges from the CommonJS spec a bit by using module. So, to use it in other common js environments root.myModule = factory(root.postal);}}(this, function(postal) {//passing this as the root argument, and our module method from earlier as the factory argument. If we run this in the browser, this, will be the window. var sub; var ch = postal.channel("myModule"); var myModule = { sayHi:function() { ch.publish("hey.yall", { msg: "myModule sez hai" }); }, dispose: function() { sub.unsubscribe(); }};return myModule;})); 
0
source

Source: https://habr.com/ru/post/1490249/


All Articles