I need some help with the concept of only loading modules when they are needed using requireJS
this is my main.js
require(['jquery', 'path/somemodule'],
function($, somemodule) {
$(document).ready(function() {
somemodule.init()
})
})
and in the somemodule.js
define(['jquery', 'path/someothermodule'], function ($, someothermodule) {
"use strict";
var somemodule;
somemodule = {
init: function () {
someothermodule.init()
}
}
return somemodule;
)}
right now somemodule.js and someothermodule.js is loaded on all pages. How do I only load it when it's needed?
When you require a module2 from module1 using the standard define() syntax module1 will not load/run until module2 has been fully loaded. That looks like this:
// inside module1
define(['module2'], function(mod2) {
// we don't get here until AFTER module2 has already been loaded
});
An alternative to lazy-load module2 looks like this:
// inside module1
define([], function() {
require(['module2'], function(mod2) {
// we don't get here until AFTER module2 has already been loaded
});
// but we DO get here without having loaded module2
});
Now you have to program somewhat carefully to make sure you don't run into any issues with asynchronicity.
In your case you can modify your main.js file
require(['jquery'],
function($) {
// jquery is loaded, but somemodule has not
if(thisPageNeedsSomeModule) {
require(['path/somemodule'],
function(somemodule) {
// now somemodule has loaded
$(document).ready(function() {
somemodule.init()
})
});
}
})
Your main.js file will load any file paths provided to it, so long as other elements of your application specify them as dependencies. See my example main.js file:
require.config({
paths: {
'app': 'app',
'underscore':'bower_components/underscore/underscore-min',
'backbone':'bower_components/backbone/backbone-min',
'marionette':'bower_components/backbone.marionette/lib/backbone.marionette.min',
'jquery': 'bower_components/jquery/jquery.min',
'tpl':'bower_components/requirejs-tpl/tpl',
'bootstrap':'bower_components/bootstrap/dist/js/bootstrap.min',
'leaflet':'bower_components/leaflet/leaflet',
'leaflet.markercluster':'bower_components/leaflet/leaflet.markercluster',
},
shim: {
'underscore': {
exports: '_'
},
'leaflet': {
exports: 'L'
},
'leaflet.markercluster': {
deps: ['leaflet']
},
'backbone': {
deps: ['underscore']
},
'marionette': {
deps: ['backbone']
},
'jquery': {
exports: '$'
},
'bootstrap': {
deps: ['jquery']
},
'app': {
deps: ['jquery', 'leaflet','bootstrap', 'leaflet.markercluster', 'marionette', 'tpl']
},
'app.elem': {
deps:['app']
},
'app.api': {
deps:['app']
}
}
})
require(['app','app.api','app.elem'], function() {
App.start();
})
And my initial application file:
define(['router', 'collections/moments'], function(router, momentCollection) {
// Boot the app!
App = new Marionette.Application();
App.LocResolve = false; // Have we resolved the user's location?
App.Locating = true; // Are we actively tracking the user's location?
App.FileReader = window.FileReader ? new FileReader : null;
App.Position = null; // Instant access to Lat & Lng of user.
App.MomentsRaw = null; // Keep cached copy of returned data for comparison.
App.Moments = new momentCollection; // Current collection of moments.
App.Markers = new L.MarkerClusterGroup(); // Create Marker Cluster Group
App.View = null; // Current view.
// Marionette Regions
App.addRegions({
header: '#header',
map: '#map',
list: '#list',
modal: '#modal',
});
return App
})
I noticed that you aren't passing in a configuration object - is this intentional? If you use R.js, the build optimizer, it will automatically remove unused vendor files for you.
In short, sets paths to your vendor files in the require.js config, then call upon them via define() whenever you need a particular asset. This will ensure that only files you need are used. Hope this helps!
Related
I created a simple app using knockout/bootstrap/gulp that downloads a pdf using pdfMake.js. It works fine in debug mode using VS2017. After publishing and using gulp it gives this error when run: File 'Roboto-Regular.ttf' not found in virtual file system
Note: After gulp, all JS files are in one script.js file.
I tried many things, it always works when debugging, as soon as I run gulp, it gives the error.
I tried joepal1976's solution from here (what I did with the dependencies in require.config.js)
Someone suggested .pipe(uglify({
compress: {
hoist_funs: false
}
})) which doesn't appear to help.
Included in require.config like so:
var require = {
baseUrl: ".",
paths: {
"jquery": "js-libs/jquery.min",
"bootstrap": "js-libs/bootstrap.min",
"crossroads": "js-libs/crossroads.min",
"hasher": "js-libs/hasher.min",
"knockout": "js-libs/knockout",
"knockout-projections": "js-libs/knockout-projections.min",
"signals": "js-libs/signals.min",
"text": "js-libs/text",
"vfs_fonts": "js-libs/vfs_fonts",
"pdfMake": "js-libs/pdfmake.min"
},
shim: {
"bootstrap": { deps: ["jquery"] },
'pdfMake':
{
exports: 'vfs_fonts'
},
'vfs_fonts':
{
deps: ['pdfMake'],
exports: 'vfs_fonts'
}
}
};
JS for the page:
define(["knockout", "text!./home.html"], function (ko, homeTemplate) {
function HomeViewModel(route) {
var thisVM = this;
this.VMInit = function () {
var thePDF = {
content: [
'My test invoice.',
]
};
pdfMake.createPdf(thePDF).download('pdf_test.pdf');
}
thisVM.VMInit();
}
return { viewModel: HomeViewModel, template: homeTemplate };
});
The Gulp file:
//-----------------------------------------------------------------------
// Node modules
var fs = require('fs'),
vm = require('vm'),
merge = require('deeply'),
chalk = require('chalk'),
es = require('event-stream');
//-----------------------------------------------------------------------
// Gulp and plugins
var gulp = require('gulp'),
rjs = require('gulp-requirejs-bundler'),
concat = require('gulp-concat'),
clean = require('gulp-clean'),
replace = require('gulp-replace'),
uglify = require('gulp-uglify'),
htmlreplace = require('gulp-html-replace');
// Config
var requireJsRuntimeConfig =
vm.runInNewContext(fs.readFileSync('src/app/require.config.js') + '; require;');
requireJsOptimizerConfig = merge(requireJsRuntimeConfig, {
out: 'scripts.js',
baseUrl: './src',
name: 'app/startup',
paths: {
requireLib: 'js-libs/require'
},
include: [
'requireLib',
'components/nav-bar/nav-bar',
'components/home-page/home',
'text!components/about-page/about.html'
],
insertRequire: ['app/startup'],
bundles: {
// If you want parts of the site to load on demand, remove them from the 'include' list
// above, and group them into bundles here.
// 'bundle-name': [ 'some/module', 'another/module' ],
// 'another-bundle-name': [ 'yet-another-module' ]
}
});
//-----------------------------------------------------------------------
// Discovers all AMD dependencies, concatenates together all required .js
files, minifies them
gulp.task('js', function () {
return rjs(requireJsOptimizerConfig)
.pipe(replace('Views/src/', ''))
.pipe(replace('img/', 'Assets/img/'))
.pipe(replace('css/', 'Assets/css/'))
.pipe(uglify({
preserveComments: 'some'
}))
.pipe(gulp.dest('./dist-app/Assets/js/'));
});
gulp.task('css', function () {
return gulp.src(['./src/css/bootstrap.css',
'./src/css/bootstrap-switch.css',
'./src/css/dataTables.bootstrap.css',
'./src/css/dataTables.colVis.css',
'./src/css/dataTables.responsive.css',
'./src/css/daterangePicker.css'])
.pipe(concat('styles.css'))
.pipe(gulp.dest('./dist-app/Assets/css/'));
});
// Copies index.html, replacing <script> and <link> tags to reference production
URLs
gulp.task('html', function () {
return gulp.src('./src/index.html')
.pipe(htmlreplace({
dependencies_top: '<link href="Assets/css/styles.css"
rel="stylesheet">',
dependencies_bottom: '<script src="Assets/js/scripts.js"></script>'
}))
.pipe(gulp.dest('./dist-app/'));
});
// Removes all files from ./dist/
gulp.task('clean', function () {
console.log("the clean task");
return gulp.src('./dist-app/**/*', { read: false })
.pipe(clean());
});
// All tasks in [] must complete before 'default' can begin
gulp.task('default', ['html', 'js', 'css'], function (callback) {
callback();
console.log('\nPlaced optimized files in ' + chalk.magenta('dist-app/\n'));
});
The Startup.js file if its helpful:
define(['jquery',
'knockout',
'./router',
'bootstrap',
'knockout-projections',
'pdfMake',
'vfs_fonts'], function ($, ko, router) {
// Components can be packaged as AMD modules, such as the following:
ko.components.register('nav-bar', { require: 'components/nav-bar/nav-bar' });
ko.components.register('home-page', { require: 'components/home-page/home'
});
// ... or for template-only components, you can just point to a .html file
directly:
ko.components.register('about-page', {
template: { require: 'text!components/about-page/about.html' }
});
ko.components.register('new-page', { require: 'components/new-page/new-page'
});
// [Scaffolded component registrations will be inserted here. To retain this
//feature, don't remove this comment.]
// Start the application
ko.applyBindings({ route: router.currentRoute });
});
Following code worked for me:
import pdfMake from "pdfmake/build/pdfmake";
import pdfFonts from "pdfmake/build/vfs_fonts";
pdfMake.vfs = pdfFonts.pdfMake.vfs;
I battled with this recently on stackblitz when using it with angular. the issue was pdfmake.vfs on the window object was not being set. so i had to manually set it in the constructor of my pdf service like so.
constructor() {
(window as any).pdfMake.vfs = pdfFonts.pdfMake.vfs;
}
I came across this issue and resolved it by including vfs_fonts.js just after the pdfmake Javascript file.
Here is my code, you should just need to set the file path to wherever your copy of the file is placed.
<script src="~/Content/DataTables/pdfmake-0.1.32/pdfmake.min.js"></script>
<script src="~/Content/DataTables/pdfmake-0.1.32/vfs_fonts.js"></script>
CDN LINK
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script>
please follow the hierarchy/dependency of links else it won't work
It is just the sequence of the files, add first the pdfmake and then vfs_fonts.
#Rijo solution worked in one file, but oddly enough refused to work in another file.
In the other file I had to use:
import pdfMake from "pdfmake/build/pdfmake";
import pdfFonts from "pdfmake/build/vfs_fonts";
// Wherever you call createPdf, you have to pass VFS
pdfMake.createPdf(docDefinition, null, null, pdfFonts.pdfMake.vfs).open();
If I configure a specific context:
var myRequire = require.config({
context: 'foo',
paths: {
'jquery': 'jquery-1.11.2'
}
});
I can then immediately use myRequire to load a module:
myRequire(['require', 'jquery'], function (require, $) { /* ... */ });
But if I move the configuration to a separate file, how do I retrieve the proper context?
Based on this answer I found that requirejs.s.contexts['foo'].require returns the same function as myRequire. That seems hacky. Another option would be to define a module for the config and return myRequire from it. What is the approved method?
This is working:
require.config.js:
define(function () {
'use strict';
var myRequire = require.config({
context: 'foo',
paths: {
'jquery': 'jquery-1.11.2'
}
});
return {
myRequire: myRequire
};
});
main.js:
// does need path and .js extension
requirejs(['/scripts/require.config.js'], function (requireConfig) {
var myRequire = requireConfig.myRequire;
myRequire(['require', 'jquery'], function (require, $) { /* ... */ });
});
I'm still open to better ways, and I have not tested this with r.js.
I was hoping that the following code would guarantee that parentClass is loaded before childClass, and that both would be loaded before startMyApp was called.
require([
"parentClass",
"childClass"
], function (parentClass, childClass){
Main.startMyApp();
});
If not, how can I guarantee that? Main, is an object. Child class is defined as such:
var childClass = function childClass() {
this.name = 'some name';
};
childClass.prototype = new parentClass();
childClass.prototype.constructor = childClass;
And here is parentClass:
var parentClass = function parentClass() {
};
parentClass.prototype.myFunction = function myFunction(){
//do something
}
I am trying to avoid adding define's to all of my classes, I've got dozens. Is that the only way to guarantee class are available when I need them? Thanks!
The call require(["parentClass", "childClass"], ... tells RequireJS to load both modules but this call does not coerce the order in which the modules are loaded. What does coerce the order of the modules are the dependencies you establish between the modules.
Since this is your own code, and you've decided to use RequireJS, then you should write proper AMD modules. To establish dependencies you list them as the first argument of your define calls (if needed). For your parent class:
define(function () {
var parentClass = function parentClass() {
};
parentClass.prototype.myFunction = function myFunction(){
//do something
}
return parentClass;
});
For your child class:
define(['parentClass'], function (parentClass) {
var childClass = function childClass() {
this.name = 'some name';
};
childClass.prototype = new parentClass();
childClass.prototype.constructor = childClass;
return childClass;
});
Then whatever other modules needs childClass just require your childClass module and parentClass is guaranteed to be loaded before childClass because parentClass is listed as a dependency in the define call.
You want to use the shim config, for example:
require.config({
paths: {
jquery: ['../bower_components/jquery/jquery.min'],
underscore: ['../bower_components/underscore/underscore-min']
app: 'app'
},
shim: {
underscore: {
deps: ['jquery'],
exports: '_'
},
waitforimages: {
deps: ['jquery']
},
cyclotron: {
deps: ['jquery']
},
placeholder: {
deps: ['jquery']
},
app: {
deps: ['jquery', 'underscore', 'fastclick', 'spinjs', 'waitforimages', 'backgroundCheck', 'raphael', 'swipe', 'history', 'cyclotron', 'placeholder']
}
}
});
require([
'app'
]);
this isn't the most optimized example, but basically, if you say that something is a dep of another script, it will make sure to load those files. So you can see in this example, I am telling require that these plugins require jquery, and my app requires jquery and these plugins.
This way everything gets loaded before my app.js
I'm using RequireJS (version 2.1.14) and would like to concatenate my JavaScript files into one single app-built.js.
I've created a little node module which reads my app.js, extracts the project paths and gets executed once I run node build in the js directory of my application.
The node module (build.js):
var fs = require('fs'),
path = require('path'),
directory = __dirname + path.sep,
requirejs = require(directory + 'vendor/r.js');
fs.readFile(directory + 'app.js', 'utf8', function(err, data) {
if (err) {
console.log('Error: ' + err);
return
} else {
data = data.replace(/'/g, '"').replace(/\s+/g, '');
var paths = data.substr(data.indexOf('{'), data.indexOf('}')),
paths = paths.substr(0, paths.indexOf('}') + 1),
paths = JSON.parse(paths);
createAppBuilt(paths);
}
});
function createAppBuilt(paths) {
var config = {
baseUrl: __dirname,
paths: paths,
name: 'app',
out: 'app-built.js',
preserveLicenseComments: false,
findNestedDependencies: true,
removeCombined: true
};
requirejs.optimize(config, function(buildResponse) {
var contents = fs.readFileSync(config.out, 'utf8');
console.log('Created app-built.js');
}, function(err) {
console.log('Error: ' + err);
return;
});
}
app.js:
var paths = {
'jquery': 'vendor/jquery-1.11.0.min',
// other paths
};
// Set language, necessary for validtaion plugin -> validation.js
if (Modernizr.localstorage) {
localStorage.getItem('language') || localStorage.setItem('language', navigator.language || navigator.userLanguage);
}
requirejs.config({
paths: paths,
shim: {
touchswipe: {
deps: ['jquery']
},
icheck: {
deps: ['jquery']
},
validate: {
deps: ['jquery']
},
mask: {
deps: ['jquery']
},
chosenImage: {
deps: ['jquery', 'chosen']
},
cookie: {
deps: ['jquery']
}
}
});
require(['globals', 'jquery', 'underscore'], function() {
var initial = ['main'];
if (!Modernizr.localstorage) {
initial.push('cookie');
}
require(initial, function(Main) {
$(function() {
if (!Modernizr.localstorage) {
$.cookie.json = true;
}
Main.init();
});
});
});
The app-built.js gets generated but when I include it in my index.php all the other modules get loaded as well. How can I prevent the loading of all modules and only load the app-built.js?
I recommend you look into http://webpack.github.io/
or http://browserify.org/ as these solve this problem for you.
They allow you to use require much as before, yet the code is compiled/concatenated into a single file.
Webpack allows for a bit more flexibility in loading different chunks of code for different parts of your site, but Browserify is the most well-known so far.
There may be a cost in switching over to these, as I don't think that they're 100% compatible requirejs, however they bring great advantages.
Here's someone's journey from RequireJS to Browserify with some Pros and Cons.
Separate modules into different files, e.g. app-built.js, user-built.js. Then load script when it's needed.
Here's a demo: http://plnkr.co/edit/s6hUOEHjRbDhtGxaagdR?p=preview .
When page loaded, requirejs only loads global.js. After clicking the Change Color button, requirejs starts to load colorfy.js and random-color.js, which required by colorfy.js.
I am not sure about the exact details, but, yet if you don't have an exports option, r.js doesn't define a named module for you, that causes to actually load the script.
I assume you have jquery plugins there so add this extra exports option:
shim: {
touchswipe: {
deps: ['jquery'],
exports: 'jQuery.fn.touchswipe'
},
This should force r.js to build a named module for touchswipe:
define("touchswipe", (function (global) {
return function () {
var ret, fn;
return ret || global.jQuery.fn.touchswipe;
};
}(this)));
Note that, exports option might not build this named module, in that case your best bet is to include this manually.
Again I am not sure about why and how this happens, It must be a bug in requirejs, it's unlikely there is a tweak for this.
Changing the r.js optimizer (to uglify2) solved the problem for me:
var config = {
baseUrl: __dirname,
paths: paths,
name: 'app',
out: 'app-built.js',
findNestedDependencies: true,
preserveLicenseComments: false,
removeCombined: true,
optimize: 'uglify2'
};
I have a requirejs module in which I am trying to load markdownjs. Here is the file:
define(function(require) {
'use strict';
var Backbone = require('backbone');
var blogCollectionTemplate = require('hbs!app.templates/blog.collection.view');
var BlogModelView = require('views/blog.item.view');
var markdown = require('markdown');
var BlogCollectionView = Backbone.View.extend({
template: blogCollectionTemplate,
initialize: function() {
debugger;
},
render: function() {
this.$el.html(this.template());
this.renderAll();
return this;
},
renderAll: function() {
var that = this;
this.collection.each(function(blog) {
that.renderItem(new BlogModelView({model: blog}));
});
},
renderItem: function(blog) {
this.$el.find('#blog-posts').append(blog.render(blog).el);
}
});
return BlogCollectionView;
});
Here is my require.config:
define(function() {
require.config({
hbs : {
templateExtension : 'hbs',
disableHelpers: true,
disableI18n : true
},
shim: {
'backbone': {
deps: [
'underscore',
'jquery'
],
exports: 'Backbone'
},
bootstrap: {
deps: [ 'jquery' ]
},
DlHighlight: {
exports: 'DlHighlight'
},
'jqueryMockAjax': {
exports: '$.mockjax',
deps: ['jquery']
},
json2 : {
exports: "JSON"
},
'underscore': {
exports: '_'
}
},
paths: {
backbone: 'libs/backbone/backbone',
bootstrap: 'libs/bootstrap/dist/js/bootstrap',
DlHighlight: 'libs/hl/hl-all',
highlight: 'libs/highlightjs/highlight.pack',
jquery: 'libs/jquery/jquery',
jqueryMockAjax: 'libs/jquery-mockjax/jquery.mockjax',
markdown: 'libs/markdown/lib/markdown',
text: 'libs/text/text',
underscore: 'libs/underscore/underscore',
hbs: 'libs/hbs/hbs',
handlebars: 'libs/hbs/Handlebars',
i18nprecompile: 'libs/hbs/hbs/i18nprecompile',
json2 : 'libs/hbs/hbs/json2',
'app.templates': '../templates/'
}
});
});
Here is the strange behavior. In my initialize, when I hit the debugger, I have access to the markdown object that I have imported, BUT if I have try to use the markdown object, then it is always undefined. If I put markdown in the initialize or in one of the render methods, the markdown variable is undefined. It makes no sense, but is there some behavior that I dont understand about requirejs. Any ideas?
After reading the code of a bower installation of markdown-js, I found that what bower installs won't work with RequireJS as-is. Try adding this shim:
"markdown": {
exports: "markdown"
}
As to why were you able to get a value for markdown in the debugger without the shim, I believe you were getting it (perhaps without realizing it) from the global scope. Markdown-js installs itself into the global scope (window.markdown, which is then accessible as markdown if no other variable interferes with it) when it is loaded. This is speculation but it fits the facts.
You can require all of those modules in the define clause itself:
define([
'backbone',
'hbs!app.templates/blog.collection.view',
'views/blog.item.view',
'markdown'
], function (
Backbone,
blogCollectionTemplate,
BlogModelView,
markdown
) {
'use strict';
// do stuff
});
Also, what do you mean by "If I put markdown in the initialize or in one of the render methods"? Do you mean actually explicitly requiring markdown in initialize and render? Is there any reason to not just load markdown in the define clause as labeled above?
If you are explicitly requiring markdown in initialize or render, I am not sure why that would return undefined, but let me know if moving requirements to the define clause fixes your issue (or if you can't do that). Perhaps you could post the code in the markdown module (if it's not a library that is)?