I was looking through file upload plugin's javascript code.
There is a piece of code which checks if define is a function and declares a few dependencies i guess
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'jquery.ui.widget'
], factory);
} else {
// Browser globals:
factory(window.jQuery);
}
}
The comments just above the code says define is global. But i dont have it in my application built using angularjs.
I searched the codebase for declaration of define. BUt couldn't find any. I googled for AMD and i could see define being used here again.
My question is where is 'define' defined?
define is a function whose functionality is defined by the Asynchronous Module Definition specification. AMD is just a spec; there's multiple implementations, of which RequireJS is one. You could see how RequireJS implements it if you want, but keep in mind that RequireJS's define isn't the only define out there.
Related
How do I require a JavaScript library that is not packaged as a UMD-compatible module (AMD, CommonJS) with webpack?
I don't want the library to pass through a loader. I just want it to be included in a <script> tag whenever it is required, and for webpack to manage this dependency.
I don't want to simply place it in a script tag in my index.html, because I want to take advantage of webpack's code-splitting, and only include it when necessary.
I've read about 'externals', I'm not sure if this has anything to do with it. The docs are not clear enough.
Thanks :)
Updated question
Also this question is specifically about front-end libraries that only need to be included via a <script> tag to work.
You can add amd support to your library and then load it with webpack.
Some links that can help you achieve are:
http://ifandelse.com/its-not-hard-making-your-library-support-amd-and-commonjs/
https://github.com/mbostock/d3/pull/1921
What is basically being done is that at the top of your library you can check whether it's a commonjs environment or an AMD environment. Accordingly you can export your library.
One example can be this ( taken from 1st link )
(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 {
root.myModule = factory(root.postal);
}
}(this, function(postal) {
// module code here....
return myModule;
}));
I'm trying to use a non-AMD JS module I have (called mymodule) in requirejs. This is the first time to try to do so. Following what I saw from bootstrap-amd, and underscore-amd, I tried the following:
// start of mymodule
if(typeof mymodule === "undefined") loaded = {};
mymodule.cache = (function() {
...
return {
...
};
})();
mymodule.main = (function() {
...
return {
doSomethingJQuery: function() { ... }
}
})();
.
.
.
// end of mymodule
// This part I added for the sake of requirejs
if(typeof define === "function" && define.amd) {
define(function() {
return mymodule;
});
}
You can see the first part is my module (using, I hope, good JS module pattern :). I wanted to keep the option of using the module independent from require JS so if I didn't want to use requirejs in another project, I don't have to. So I kinda didn't want to wrap the entire module in a define(...) function... unless it's common practise to have a mymodule.js and mymodule-amd.js files.
Anyway my module loads,
define(["mymodule"], function (mymodule) {
// do it - ReferenceError: jQuery is not defined :(
mymodule.doSomethingJQuery();
.
.
.
..but as doSomethingJQuery() depends on jQuery, I get an error. How can I bring in jQuery here, or should it be done differently? I tried to find some examples but pretty new to requirejs. Would like to do things in the proper way. As mentioned, I'd like to also keep the option to use the module independently. Would appreciate any pointers here, thanks.
You need to make your module dependent on jQuery and pass the reference to a function that will define your module. Change the code that defines your module to:
if(typeof define === "function" && define.amd) {
define(['jquery'], factory);
}
else
mymodule = factory(jQuery);
The else part is necessary for cases that are not AMD because you're now using a factory function. (You could also have a branch to deal with CommonJS environments like Node but I'm not going to add it here.)
Then make a function that defines your module:
function factory($) {
// define the module
return mymodule;
}
The entire thing could be wrapped in an IIFE to avoid polluting the global space with factory.
I have a library - call it SomeLib - which is defined to support various module loaders:
(function(global, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = factory();
} else {
global.UriTemplate = factory();
}
})(this, function() {
...
// returns constructor function
});
I can easily load it with RequireJS like
require.config({
paths: {
'theLibrary: '../path/to/the/lib'
}
});
Then I have another 3rd-party library - call it AnotherLib - which internally uses SomeLib like
var the Lib = new SomeLib(...);
That means SomeLib has to be available globally.
AnotherLib is just a plain JavaScript module function
(function(){
// the code
})();
It is not compliant with particular module loaders.
When I include AnotherLib with RequireJS, I do something like
require.config({
paths: {
'theLibrary: '../path/to/the/lib',
'anotherLib: '../path/to/anotherLib'
},
shim: {
'anotherLib: [
'theLibrary'
]
}
});
The problem is that I get a undefined exception on the line within AnotherLib where it instantiates SomeLib (new SomeLib(...)).
This is because SomeLib is not defined on the global object but rather published as an AMD module which AnotherLib doesn't "require".
Can I solve this somehow, or does AnotherLib have to be AMD compliant and properly require SomeLib.
The best thing would be to get an AMD-compliant library or to make the library AMD compliant. The latter option would entail modifying the source manually or having a build step that turns the non-AMD-compliant code into a real AMD module. How to do this depends on how the library is designed.
An method that would work with any library is to deliberately leak the symbol that the library requires into the global space:
Make anotherLib be dependent on a new module, which you could call SomeLib-leak.
Create the new module. This definition does not have to be in a separate file. I usually place such "glue" modules before my call to require.config. The module would be like this:
define('SomeLib-leak', ['SomeLib'], function (SomeLib) {
window.SomeLib = SomeLib;
});
I do purposely have define set the module name here. Usually, you don't want to call have define set the module name but for "glue" modules that are placed like I indicated above, this is necessary.
By the time anotherLib is loaded, SomeLibrary will be in the global space.
Say you've got a ViewModel (or other RequireJS module) that looks like this:
define(['plugins/dialog'], function (dialog: /* what type should go here? */) {
/* rest of module */
}
For reference, the type we are interested is the Dialog interface, which is defined like this in durandal.d.ts:
declare module 'plugins/dialog' {
interface Dialog {
owner: any;
context: DialogContext;
activator: DurandalActivator<any>;
close(): JQueryPromise<any>;
settings: composition.CompositionContext;
}
}
This type of module definition is referred to as an "ambient external module declaration." As #basarat noted here, you need to use import in order to gain access to these modules. Here's how your ViewModel needs to be updated:
import dialogModule = require('plugins/dialog');
define(['plugins/dialog'], function (dialog: dialogModule.Dialog) {
/* rest of module */
}
This works at compile time, but the generated JavaScript now looks like this:
define(["require", "exports"], function(require, exports) {
define([
/* rest of module */
});
});
You can see that the module was wrapped in an extra "define()" call. This results in a mismatched anonymous define error when you try to show the dialog (i.e., when Durandal tries to retrieve this module).
So, is it possible to "import" and make use of types inside ambient external module declarations, without it wrapping your file in an extra define()?
Ideally, the Durandal .d.ts would be written differently (such that you could access the interface without importing the module).
As a practical solution, you could compile your file with --module commonjs instead of --module amd. The require call will be optimized away and you'll still get type information.
You could also compile with --module amd and rewrite your code to not explicitly call define (just let the compiler generate that, like it's trying to), though I'm assuming you've avoided doing that for intentional reasons.
I'm using requirejs in a somewhat special JS environment where an application provides a global singleton (I cannot change this fact, this isn't running in a typical browser environment). I am writing a sort of JS SDK for this application and want to provide various modules that use this global.
Can I wrap that global in a module somehow in order to require it from my modules? Something like
define([the_global_application], function(app)
Thanks for your thoughts on this.
Yes, you just have to define it.
// mysingletonapp.js
// define the module for our global var
define(['list', 'any', 'dependency', 'here'], function (l, a, d, h) {
return yourGlobalVariable;
});
(I don't think you'll have dependencies in there, since you're just wrapping a global var)
The you can use that module as usual:
require(['mysingletonapp'], function (app) {
// do something cool
});
If you want to skip all this, you can use the shim property of RequireJS. You would just need to add this to your options file:
...
shim: {
'globalApplication': {
deps: ['underscore', 'jquery'], // again, you should not need them
exports: 'yourGlobalVar'
}
}
...
shims wrap libraries that don't support AMD, so to have this setting work, you would need a js for globalApplication. This isn't your case.