dropzone amd requirejs issue - javascript

I'm new to requirejs and I have a problem loading dropzonejs (http://www.dropzonejs.com/) as an AMD .
My requirejs config is:
requirejs.config({
baseUrl: 'js/MV'
,paths: {
,jquery: '../libs/jquery-latest'
handlebars: '../plugins/handlebars'
,scrolltofixed: '../plugins/scrolltofixed'
,logout: '../logout'
,dropzone: '../plugins/dropzoneAmdModule'
}
});
When I try to load the dropzone module with
function _activateDropzone(){
require(['dropzone'], function(dropzone){
var pippo = new Dropzone({ //..config
});
});
}
it logs
Uncaught ReferenceError: Dropzone is not defined
even if I'm loading the dropzone-amd-module .
Any advice?

With RequireJS you have to use the return value in the callback function. In your example you are using dropzone (lower case) as the module return value, but in the code you then use Dropzone (upper case). I think this should work:
function _activateDropzone(){
require(['dropzone'], function(Dropzone){
var pippo = new Dropzone({ //..config
});
});
}
dropzone-amd-module is detecting that is is being used within AMD loader and instead of adding Dropzone to the global scope it returns a local value to the module loader.

Related

What will be format of first define() and require() function in requirejs project

Question#1: After requirejs configuration, what will be the format of first require() call to load my main.js
App.js
requirejs.config({
baseUrl: 'lib',
paths: {
app: '../app'
}
});
require(['app/main'], function(m){
console.log('loading m...');
});
Question#2: And what will be format of first define() function in main.js file.
Main.js
define(function () {
var messages = require('./messages');
var print = require('print');
});
The only issue I see in the code you show is that your main.js should have its define call like this:
define(function (require) {
var messages = require('./messages');
var print = require('print');
});
If you pass a function as the first parameter to define, RequireJS will call it with the special modules require, exports and module but at a minimum you must declare the first parameter so that the calls you made inside your factory function are to the local require (passed to the function) rather than the global require. There are a number of issues if you call the global require. One of them is that relative module references like ./messages won't be resolved correctly.
The require call you have in your app.js looks fine.

How to properly load local AMD modules with jspm/system.js

I am having a really hard time using local AMD modules in an Aurelia project that uses es6, JSPM, and system.js. I am hoping someone out there can help me configure my project to enable me to import/load my AMD modules and use them in my project. The local AMD style modules are in a format similar to the following:
define
(['require',
'lib/alerts/STARTSTOP',
'lib/alerts/STOPPED',
...
],
function( require, STARTSTOP, STOPPED, ... ) {
return {
alert: function( data ) {
var type = data.type;
var ev = data.event;
var cls = require( 'lib/alerts/' + ev );
return new cls( data );
}
};
});
When I try to import/load this module into an es6 module I am running into the following error: Uncaught TypeError: Unexpected anonymous AMD define.. I get this error when trying to load the module in either of the following ways:
System.import('lib/alerts/AlertFactory').then( (m) => {
console.log( m );
});
or
import AlertFactory from 'lib/alerts/AlertFactory.js';
I have also made sure to add the following script to my index.html:
<script>
window.define = System.amdDefine;
window.require = window.requirejs = System.amdRequire;
</script>
In addition to the above I have also added a meta format property to my config.js file, but that hasn't seemed to help either.
meta: {
...
"lib/alerts/*.js": {
"format": "amd"
}
}
Does anyone have any ideas on why I am running into the error I am seeing and how to properly load my modules? I appreciate any help/insight you can offer.
UPDATE
I finally realized that the main issue here is that I'm trying to use existing AMD modules in and Aurelia project, and the default Aurelia gulp build assumes that all code is written in ES6 and not mixed with AMD. That's why I'm having issues. Vanilla jspm/system.js handle a mix of module formats, but Aurelia does not out of the box.
Just put your AMD modules out of src so babel will not be able to transpile it. Here is working solution I use to import jquery modules:
First, I have local_packages folder in project root and I have jquery module local_packages/somelib/js/mymodule.js
Then in config.js
paths: {
...
"local/*": "local_packages/*",
}
map: {
...
"somelib": "local/somelib",
"somelib1": "/local_packages/somelib1",
}
And finally my import looks like: import 'somelib/js/mymodule';

Require module defined in another script

Script A
;(function(g){
define('hotness', [], function() {
function f() {;
console.log('gotem');
}
return f;
});
define('otherModule', [], function() {});
})(this);
Script B
define([
'ScriptA',
], function() {
var hotness = require('hotness')
});
Error: Module name "hotness" has not been loaded yet for context: _
What is the recommended way to require in a definition from ScriptA in ScriptB?
I've also tried:
Script B Alt
define([
'require',
'ScriptA',
'hotness'
], function(require) {
var hotness = require('hotness')
});
Which gives me
Error loading resource ... /hotness.js: No such file or directory
Error: Script error for: hotness
EDIT:
It's important to note that ScriptA stands as is and will not be modified. The question is how can I get at the named module in ScriptA from ScriptB.
EDIT2:
I have no control over the HTML or any other aspect of the page. I must do everything within ScriptB.
EDIT3:
I have an example of something that works but it looks like a horrible antipattern work-around so I didn't even want to mention it:
define(['require'], function(require) {
// why use window? IDK.
// this is just verbatim what is "working" for someone else
window.require(['scriptA'], function(sA) {
//sA never actually used
window.require([
'otherModule'
], function(oM) {
var hotness = require('hotness'),
You should use a bundles configuration. Given what you've described works, you should use:
bundles: {
'scriptA': ['hotness', 'otherModule']
}
This essentially tells RequireJS "when you want to find hotness or otherModule then load scriptA because they are defined there". I use this every now and then to load modules from bundles that have been generated with r.js.
Other than this Joseph the Dreamer is correct that you should not in the same module mix the AMD and CommonJS methods of getting dependencies.
Your ScriptA uses named modules. They must be loaded after RequireJS but prior to any of the dependents. RequireJS does not recommend named modules unless you know what you're doing (like load a library like a regular script, and register it as a module at the same time).
Error: Module name "hotness" has not been loaded yet for context: _
This is a generic RequireJS error, when the module is loaded from the server, but somehow RequireJS can't provide it to the dependent. Usually happens when the module has syntax errors or when there's a circular dependency, among others.
ScriptB also has problems. It's trying to use both AMD style (array dependencies) and CommonJS style (explicit require). Just use one of the two syntaxes. Note that in the CommonJS format, it needs the module to have a first argument named require to trigger CommonJS format of writing.
define(['hotness'], function(hotness) {
// use hotness
});
// or
define(function(require){
var hotness = require('hotness');
// use hotness
});
Error loading resource ... /hotness.js: No such file or directory
Be sure to set a base url. It can be implicit (based on the data-main location) or explicit (using require.config). Module names are usually paths + filenames relative to the base url.
It is advised that you use one file per module, containing a module definition that has no name (the file name becomes the name of the module) and resides somewhere under the set baseUrl.

how to access config.paths after it is defined in main.js

Here is my main.js
requirejs.config({
baseUrl: '/js',
paths: {
jquery: 'jquery',
ckeditor: 'ckeditor/ckeditor',
juiAutocomplete: 'jquery-ui-1.10.4.custom',
tags: 'bootstrap-tokenfield',
createPost: 'createPost',
domReady: 'domReady',
test: 'dropUpload'
},
shim: {
createPost: {
deps: ['domReady!']
}
},
deps: ['require'],
callback: function(require) {
'use strice';
var moduleName = location.pathname.replace(/\//g, '-').replace(/^-/, '');
console.log('moduleName is: ' + moduleName);
console.log('yes is: ' + require.config);
}
});
In the callback, I'd like to access the paths which is defined in the requirejs.config() above. If it is possible, how to do it?
My purpose is to see if a module path is defined(exists). If so, then load the module script. If not checked, then a loading error will generate in the console.
Here are the available methods in requirejs by this console command. I can't find a way to access the paths I defined in requirejs.config(). Is this the right direction?
for (var i in requirejs) {console.log(i);}
config
nextTick
version
jsExtRegExp
isBrowser
s
toUrl
undef
defined
specified
onError
createNode
load
exec
undef
There is no public API to get the whole RequireJS configuration from inside a module. You can have a config section in your configuration, which modules may access.
However, the problem you describe trying to solve does not require you to read the configuration. Calling require the normal way will load the module. If the module can't be loaded, it will generate an error on the console. Presumably you also want your code to know whether the loading was successful or not. You can do it with an errback:
require(['foo'], function (foo) {
// Whatever you'd like to do with foo on success.
}, function (err) {
// Whatever you'd like to do on error.
});
If for some reason you must read the config directly then it is located at requirejs.s.contexts.<context name>.config where <context name> is the name of the RequireJS context. The default context is named _ so the configuration for it would be requirejs.s.contexts._.config. However, this is not part of the public API and can change at any time.

loading multiple modules using requireJS in latest firefox 21.0 fails

I tried with 3 diff modules as defined below
credit.js
define(function(){
return{
getCredits: function (){
console.log("Inside getCredits");
return 10;
}
}
});
product.js
define(function(){
console.log("Inside product");
return {
bookTheProduct: function(){
console.log("Inside bookTheProduct");
return true;
}
}
});
pruchase.js
require.config({
shim: {
purchase: {
deps : ["credit","product"]
}
}
});
define(["credit","product"], function(credit,product){
console.log("purchaseproduct");
return {
purchaseProduct: function (){
console.log("Inside of PurchaseProduct");
var credits = credit.getCredits();
if(credits > 0){
product.bookTheProduct();
return true;
}
return false;
}
}
});
used it in app.js
require(["purchase"],function(purchase){
purchase.purchaseProduct();
})
Tried this in firefox 21.0 , while loading purchase it loaded credit module but never loaded product module . If i reverse the order it loads the product module but not the credit module . Didn't find any help in RequireJs documentation nor in mozilla documentation . Also didn't see anyone cribing abt it . did any body ever faced this problem ? I am doing some thing wrong , if so can you please point me the mistake .
thanks
As mentioned in the comments, the shim configuration is for Javascript files that do not support AMD module definitions and is used to import for example javascript libraries that add some variable to the window scope (like jQuery). Read more about shim here.
In your case, all your modules are AMD modules (they are all defined using define), so shim is not necessary. Instead you can just use the paths configuration to create aliases for your modules. Also moving your require.config out of the modules and into where your require call happens is recommendable.
So, remove the require.config from your purchase.js -file, then add the following to the beginning of your app.js -file
require.config({
// with the paths -config, you create aliases for you modules
// basically you tell require that this file contains definition for module x
paths: {
'purchase': 'path/to/purchase', // no .js file ending in the path
'credit': 'path/to/credit',
'product': 'path/to/product'
}
});
You can read more about require.config here.
Now you have configured RequireJS so, that it knows where the modules purchase, credit and product are located and that it will load them. After this they can be referenced with their respective aliases when declaring RequireJS dependencies.
Hope this helps!

Categories

Resources