require.js optimization: deep dependencies - javascript

I'm trying to optimize (i.e. build) my app which is dependent from ember-data. So as the path for ember-data I set this file https://github.com/emberjs/data/blob/master/packages/ember-data/lib/main.js but r.js includes only this particular file and omit it's dependencies. I thought maybe it's because of some kind of paths issue but I can't see any error messages in console.

Make sure that in your build file (the one you pass to r.js as a build config), you have:
findNestedDependencies: true
R.js is omitting so called "inline dependencies" by default so if you do have in your main.js i.e.
require(["sth"],function(){
require(["sthelse"]);
});
R.js will only load "sth" by assuming that "sthelse" should be loaded during runtime.
; )

Related

Is there a way to cause the JS engine to load a .js file without explicitly importing something from it?

Maybe I'm trying to do something silly, but I've got a web application (Angular2+), and I'm trying to build it in an extensible/modular way. In particular, I've got various, well, modules for lack of a better term, that I'd like to be able to include or not, depending on what kind of deployment is desired. These modules include various functionality that is implemented via extending base classes.
To simplify things, imagine there is a GenericModuleDefinition class, and there are two modules - ModuleOne.js and ModuleTwo.js. The first defines a ModuleOneDefinitionClass and instantiate an exported instance ModuleOneDefinition, and then registers it with the ModuleRegistry. The second module does an analogous thing.
(To be clear - it registers the ModuleXXXDefinition object with the ModuleRegistry when the ModuleXXX.js file is run (e.g. because of some other .js file imports one of its exports). If it is not run, then clearly nothing gets registered - and this is the problem I'm having, as I describe below.)
The ModuleRegistry has some methods that will iterate over all the Modules and call their individual methods. In this example, there might be a method called ModuleRegistry.initAllModules(), which then calls the initModule() method on each of the registered Modules.
At startup, my application (say, in index.js) calls ModuleRegistry.initAllModules(). Obviously, because index.js imports the exported ModuleRegistry symbol, this will cause the ModuleRegistry.js code to get pulled in, but since none of the exports from either of the two Module .js files is explicitly referenced, these files will not have been pulled in, and so the ModuleOneDefinition and ModuleTwoDefinition objects will not have been instantiated and registered with the ModuleRegistry - so the call to initAllModules() will be for naught.
Obviously, I could just put meaningless references to each of these ModuleDefinition objects in my index.js, which would force them to be pulled in, so that they were registered by the time I call initAllModules(). But this requires changes to the index.js file depending on whether I want to deploy it with ModuleTwo or without. I was hoping to have the mere existence of the ModuleTwo.js be enough to cause the file to get pulled in and the resulting ModuleTwoDefinition to get registered with the ModuleRegistry.
Is there a standard way to handle this kind of situation? Am I stuck having to edit some global file (either index.js or some other file it references) so that it has information about all the included Modules so that it can then go and load them? Or is there a clever way to cause JavaScript to execute all the .js files in a directory so that merely copying the files it would be enough to get them to load at startup?
a clever way to cause xxJavaScriptxx Node.js to execute all the .js files in a directory:
var fs = require('fs') // node filesystem
var path = require('path') // node path
function hasJsExtension(item) {
return item != 'index.js' && path.extname(item) === '.js'
}
function pathHere(item) {
return path.join('.', item)
}
fs.readdir('./', function(err, list) {
if (err) return err
list.filter(hasJsExtension).map(pathHere).forEach(require) // require them all
})
Angular is pretty different, all the more if it is ng serve who checks if your app needs a module, and if so serves the corresponding js file, at any time needed, not at first load time.
In fact your situation reminds me of C++ with header files Declaration and cpp files with implementation, maybe you just need a defineAllModules function before initAllModules.
Another way could be considering finding out how to exclude those modules from ng-serve, and include them as scripts in your HTML before the others, they would so be defined (if present and so, served), and called by angular if necesary, the only cavehat is the error in the console if one script tag is not fetched, but your app will work anyway, if it supposed to do so.
But anyway, it would be declaring/defining those modules somewhere in ng-serve and also in the HTML.
In your own special case, and not willing to under-evalute ng-serve, but is the total js for your app too heavy to be served at once? (minified and all the ...), since the good-to-go solution may be one of the many tools to build and rebuild your production all.js from your dev js folder at will, or like you said, with a drag&drop in your folder.
Such tool is, again, server-side, but even if you only can push/FTP your javascript, you could use it in your prefered dev environment and just push your new version. To see a list of such tools google 'YourDevEnvironment bundle javascript'.
To do more with angular serve and append static js files under specific conditions, you should use webpack so the first option i see here is eject your webpack configuration and after that you can specify what angular should load or not.
With that said, i will give an example:
With angular cli and ng serve any external javascript files you wanna include, you have to put them inside the scripts array in the angular-cli.json file.However you can not control which file should be included and which one not.
By using webpack configuration you can specify all these thing by passing a flag from your terminal to the webpack config file and do all the process right there.
Example:
var env.commandLineParamater, plugins;
if(env.commandLineParamater == 'production'){
plugins = [
new ScriptsWebpackPlugin({
"name": "scripts",
"sourceMap": true,
"filename": "scripts.bundle.js",
"scripts": [
"D:\\Tutorial\\Angular\\demo-project\\node_moduels\\bootstrap\\dist\\bootstrap.min.js",
"D:\\Tutorial\\Angular\\demo-project\\node_moduels\\jquery\\dist\\jquery.min.js"
],
"basePath": "D:\\Tutorial\\Angular\\demo-project"
}),
]}else{
plugins = [
new ScriptsWebpackPlugin({
"name": "scripts",
"sourceMap": true,
"filename": "scripts.bundle.js",
"scripts": [
"D:\\Tutorial\\Angular\\demo-project\\node_moduels\\bootstrap\\dist\\bootstrap.min.js"
],
"basePath": "D:\\Tutorial\\Angular\\demo-project"
}),
]
}
then:
module.exports = (env) => {
"plugins": plugins,
// other webpack configuration
}
The script.js bundle will be loaded before your main app bundle and so you can control what you load when you run npm run start instead of ng-serve.
To Eject your webpack configuration, use ng eject.
Generally speaking, when you need to control some of angular ng-serve working, you should extract your own webpack config and customize it as you want.

Generate RequireJS "bundles" config dynamically with Grunt

According to the RequireJS API, the bundles configuration property is used to map modules to their bundle files (in production mode, assuming you have multiple bundles on large-scale projects).
I use Grunt for bundling with r.js of course, how can I generate the bundle configuration dynamically, according to the actual bundling? e.g. if module angular was bundled to common.js, then it should be added to the list of modules of the common bundle.
This part of requirejs configuration should not be maintained manually, as it will result in many mistakes.
Any suggestions?
Version 2.2.0 of RequireJS introduced a new optimizer option to write out a bundles option that is generated from the build:
//Introduced in 2.2.0. Path to file to write out bundles config
//(http://requirejs.org/docs/api.html#config-bundles) found in the module
//layers built by the optimizer. The path is relative to the "dir" config's
//path. Only applies to full project optimization:
//http://requirejs.org/docs/optimization.html#wholeproject
//Only use if the optimized layers are grouped more intricately then just
//a simple optimization of main app entry points. The file path specified
//should be to one that has the top level requirejs.config() call that sets
//up the loader. If using "mainConfigFile", then this path likely should be
//the path to that file where it is placed in the "dir" output directory.
bundlesConfigOutFile: 'some/path/to/main.js',
If the option above does not work for you, then you'll have to do what I did and roll your own code to generate a proper value for bundles.

Webpack and clientside module loading

I'm comparing how RequireJS and Webpack works, and there's something I still don't get:
RequireJS is loaded in the browser through a <script> tag, e.g.:
<script data-main="scripts/main.js" src="scripts/require.js"></script>
In its simplest implementation, it uses the data-main attribute to set its base path and loads asynchronously every js in it
Webpack works in Nodejs environment. You install it via npm install cmd. Then you set the entry point and other stuffs in the webpack.config file
module.exports = {
entry: './src/app.js',
output: {
path: './bin',
filename: 'app.bundle.js'
}
};
When you run webpack cmd your entry point is read and its dependencies are loaded and bundled together in the output file (in this case, app.bundle.js).
This two behaviors seems to me really differents (RequireJS run and loads in browser, Webpack in Node), and I don't understand why this two module system are mentioned as interchangeable.
In particular it seems to me that webpack doesn't do anything special, it only concatenates a bunch of js together. What am I missing?

Make pdf.js 1.5 and require.js play nice together

In my project I have long used require.js together with the pdf.js library. Pdf.js have until recently been putting itself on the global object. I could still use it in my requirejs config by using a shim. The pdfjs library will in turn load another library called pdf.worker. In order to find this module the solution was to add a property to the global PDFJS object called workerSrc and point to the file on disk. This could be done before or after loading the pdfjs library.
The pdfjs library uses the pdf.worker to start a WebWorker and to do so it needs the path to a source file.
When I tried to update the pdfjs library in my project to a new version (1.5.314) the way to load and include the library have changed to use UMD modules and now everything get's a bit tricky.
The pdfjs library checks if the environment is using requirejs and so it defines itself as a module named "pdfjs-dist/build/pdf". When this module loads it checks for a module named "pdfjs-dist/build/pdf.worker". Since I have another folder structure I have added them to my requirejs config object with a new path:
paths: {
"pdfjs-dist/build/pdf": "vendor/pdfjs/build/pdf",
"pdfjs-dist/build/pdf.worker": "vendor/pdfjs/build/pdf.worker"
}
This is to make the module loader to find the modules at all. In development this works great. When I try to use the requirejs optimizer in my grunt build step however, it will put all of my project files into one single file. This step will try to include the pdf.worker module as well and this generates an error:
Error: Cannot uglify2 file: vendor/pdfjs/build/pdf.worker.js. Skipping
it. Error is: RangeError: Maximum call stack size exceeded
Since the worker source needs to be in a single file on disk I don't want this module to be included.
So I've tried two different config-settings in the requirejs config.
The first attempt was to override the paths property in my grunt build options:
paths: {
"pdfjs-dist/build/pdf.worker": "empty:"
}
The second thing to test is to exclude it from my module:
modules: [{
name: "core/app",
exclude: [
"pdfjs-dist/build/pdf.worker"
]
}]
Both techniques should tell the optimizer not to include the module but both attempts ended up with the same error as before. The requirejs optimizer still tries to include the module into the build and the attempt to uglify it ends up with a RangeError.
One could argue that since the uglify step fails it will not be included and I can go about my bussiness, but if the uglify step should happen to start working at a new update of pdfjs - what then?
Can anyone help me figure out why the requirejs config won't just exclude it in the build step and how to make it do so.
I found out what the core of my problem was and now I have a way to solve the problem and make my build process to work. My build step in grunt is using grunt-contrib-requirejs and I needed to override some options in the config for this job.
I didn't want the pdf.worker module to be included in my concatenated and minified production code.
I didn't want r.js to minify it only to later exclude it from the concatenated file.
I tried to solve the first problem thinking that it would mean that the second problem also should be solved. When I figured out the two were separate I finally found a solution.
In the r.js example on github there is a property named fileExclusionRegExp. This is what I now use to tell r.js not to copy the file over to the build folder.
fileExclusionRegExp: /pdf.worker.js/
Second, I need to tell the optimizer to not include this module in the concatenated file. This is done by overriding the paths property for this module to the value of "empty:".
paths: {
"pdfjs-dist/build/pdf.worker": "empty:"
}
Now my grunt build step will work without errors and all is well.
Thanks to async5 for informing me about the bug with uglify and the pdf.worker. The workaround is applied in another grunt task that uglify the worker and copies it into the build-folder separately. The options object for the grunt-contrib-uglify task will need this property in order to not break the pdf.worker file:
compress: {
sequences: false
}
Now my project works great when built for production.

Loading specific module from concatenated file using RequireJS

Trying to use the URI.js library in a project, but having trouble with RequireJS. URI's readme indicates that it works with requirejs - which is true when you're using the source - but not when using the minified/concatenated distribution file on its own - as you would in production.
Their build process scoops several libraries into a single .min file, and they all define themselves as modules.
No matter how I require that script, the only argument I receive is the first module in their distribution file (IPv6) which is not what I need.
Is there something trivial I'm missing?
<script>
require.config({
paths: {
urijs: 'dist/URI'
}
});
require(['urijs'], function(URI) {
console.log(URI);
});
</script>
Indeed the minified file cannot be used because it is not correctly built. All the define calls in it are anonymous whereas they should include the module name. If they had, you'd be able to use the minified file.
To get it to work, in the paths configuration, I've put urijs to point to the directory that contains all the individual .js files of the modules, and then I require URI.js as 'urijs/URI'. I let r.js minify it for distribution of my code.
I've installed it with npm but I've just checked with bower and the process should be exactly the same.

Categories