I want to merge multiple modules into a single file, but I can't find an official document about how to do it. Now I'm using the below method, it works, but I'm wondering about the following:
index.html
<script src="require.js"></script>
<script>
requirejs.config({
paths: {
'a': 'test',
'b': 'test'
}
});
require(['a', 'b'], function () {
console.log('a & b loaded');
});
</script>
test.js
console.log('loading test.js');
// I have some init here, like "Avoid `console` errors in IE"
define('a', function () {
console.log('a module');
});
define('b', function () {
console.log('b module');
});
Shim is a mechanism that RequireJS provides in order to support libraries and scripts that do not express their dependencies via define() . In other words, shim is there for traditional scripts not supporting definition of AMD modules.
RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.
RequireJS, like LABjs, allows for asynchronous JavaScript loading and dependency management; but, RequireJS uses a much more modular approach to dependency definitions. This is just an initial exploration of RequireJS. RequireJS seems to be quite robust and includes optimization and "build" tools for deployment.
With require , you can include them in your JavaScript files and use their functions and variables. However, if you are using require to get local modules, first you need to export them using module.
Shangan is right. In http://requirejs.org/docs/api.html#define there is a part that says:
There should only be one module definition per file on disk.
But if you want to do it anyway I found something like that: It is from official documentation: http://requirejs.org/docs/api.html#config-bundles
It says that you can define in which file you can find which modules by bundles
property. For example: I have file called
modules.js with such content:
define('module_one', function(){
return 'Hello. I am module one';
})
define('module_two', function(){
return 'Hello. I am module two';
})
Then in my main.js file I do something like this:
requirejs.config({
baseUrl : 'modules/',
bundles: {
'modules': ['module_one', 'module_two']
}
})
require(['module_one', 'module_two'], function(moduleOne, moduleTwo){
alert(moduleOne);
alert(moduleTwo);
})
And it works like I want to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With