Question

I'm using the RequireJS optimizer to optimize modules that also use the text plugin. In order to not have the text! plugin loaded over and over again with each optimized module, I do this

node r.js -o stubModules=text name=Main out=main-master-built.js

Which works, producing in part the following

define("text",{load:function(e){throw new Error("Dynamic load not allowed: "+e)}})
define("text!f.htm",[],function(){return"<h3>Hello World</h3>\r\n<h4>Bam</h4>"})

Unfortunately, as the above shows, I can no longer use the text plugin "normally." The error-throwing stub above prevents me from adding a text! call to an un-optimized dependency list.

Is there any way around this? Is there any option I can put in that would, say, change these text references on the fly to texto and then do something like

define("texto",{load:function(e){throw new Error("Dynamic load not allowed: "+e)}})
define("texto!f.htm",[],function(){return"<h3>Hello World</h3>\r\n<h4>Bam</h4>"})

Or some other option that will optimize modules with text dependencies while not also killing my ability to keep using it dynamically?

Was it helpful?

Solution

Here's the deal. If everything loaded through text! has been optimized with r.js, then all text has been included in the output of r.js, and you can stub the plugin.

However, if you want to have the ability to use text! to load text that has not been through the optimization process, then you must have the text! plugin available at run time. In this case you cannot stub it, otherwise RequireJS won't be able to load the text pieces that you have not optimized because there won't be a text! plugin for RequireJS to use.

In an application that contains modules loaded by text! that have been optimized and modules loaded by text! that have not been optimized, the following will happen:

  • For a module that has been optimized, RequireJS will find a define call with module's name (because this is part of what r.js does). For instance, define("text!foo", [...], function(...). In a case like this, RequireJS will not try to use the text! plugin to load this module. It will just load the module directly. (This has to be true otherwise stubbing the text! plugin would cause RequireJS to fail as soon as any optimized module that uses text! is required.)

  • For a module that has not been optimized, RequireJS will ask text! to load the module.

Unless special measures are taken, r.js automatically includes the entire text! plugin when it finds it among the dependencies of a bundle of modules.

So to exclude the text module specifically, use the excludeShallow option. Your new command line/bat file would look something like this:

node r.js -o name=Main excludeShallow=text out=main-master-built-text-path.js
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top