javascript - Using define() in require.js -
i'm started learning using require.js
main.jsrequire(['jquery', 'underscore', 'module1'], function($, _, module1) { module1.init(); $('#output').html('hello world!'); });
module1.js define('module1', [], function(app) { var init = function() { alert('hello world!') ; } return { init: init }; });
it's working i'm wondering can change define('myapp', [] function(app){});
in module1.js?, , modify main.js to
require(['jquery', 'underscore', 'myapp'], function($, _, myapp) { myapp.init(); $('#output').html('hello world!'); });
please help, can understand more using require.js.
thanks.
edited
with below answer, i've modified coding to
module1.jsdefine('myapp', [], function(app) { var init = function() { alert('hello world!') ; } return { init: init }; });
main.js require.config({ baseurl: 'js', paths: { module1: 'module1' } }); require(['jquery', 'underscore', 'module1'], function($, _, myapp) { myapp.init(); $('#output').html('hello world!'); });
unfortunately still couldn't work, please give me more advices.
in define part you're defining myapp
a dependency of module, not name of module itself. search requirejs.config part , change name of module.
requirejs.config({ paths: { 'module1': '../somepath/module1.js', // change module1 myapp ... } });
when you've changed name of module can initialize module this:
require(['myapp'], function(myapp) { myapp.init(); });
edit
you need define other modules/plugins well.
main.js
require.config({ baseurl: 'js', paths: { 'myapp': 'module1', 'jquery': 'jquery.min', 'underscore': 'underscore.min' } }); require(['jquery', 'underscore', 'myapp'], function($, _, myapp) { myapp.init(); $('#output').html('hello world!'); });
module1.js
define(function() { var init = function() { alert('hello world!'); }; return { init: init }; });
you can define name of module in module wouldn't advice it. require.js doc:
you may encounter define() calls include name module first argument define() [...] these generated optimization tool. can explicitly name modules yourself, makes modules less portable -- if move file directory need change name. best avoid coding in name module , let optimization tool burn in module names. optimization tool needs add names more 1 module can bundled in file, allow faster loading in browser.
Comments
Post a Comment