Require, Knockout and pager are Undefined TypeError - requirejs

I have the following main:
requirejs.config({
paths:{
'text':'../vendor/js/text.min',
'jquery':"../vendor/js/jquery.min",
'boostrap':"../vendor/js/bootstrap.min",
'ko':"http://knockoutjs.com/downloads/knockout-3.4.0.debug",
'pager':"../vendor/js/pager",
'imageGroupsVm':'../js/viewModels/imageGroupsViewModel',
'panelVm':'../js/viewModels/panelViewModel',
'compMessage':'../js/components/message',
'extBooleanToggle':'../js/extenders/booleanToggle'
},
shim:{
'bootstrap':['jquery'],
'pager':['ko'],
},
waitSeconds: 200,
});
define(['jquery','ko','pager','panelVm'],function($,ko,pager,panelVm)
{
pager.extendWithPage(panelVm);
ko.applyBindings(panelVm);
pager.start();
});
But for some reason I get these 2 error messages:
TypeError: ko is undefined
Stack trace:
pagerJsModule#http://localhost/symphotest/assets/vendor/js/pager.js:150:9
#http://localhost/symphotest/assets/vendor/js/pager.js:1506:20
newContext/context.execCb#http://localhost/symphotest/assets/vendor/js/require.min.js:1690:24
newContext/Module.prototype.check#http://localhost/symphotest/assets/vendor/js/require.min.js:865:43
newContext/Module.prototype.enable/</<#http://localhost/symphotest/assets/vendor/js/require.min.js:1140:29
bind/<#http://localhost/symphotest/assets/vendor/js/require.min.js:131:20
newContext/Module.prototype.emit/<#http://localhost/symphotest/assets/vendor/js/require.min.js:1190:21
each#http://localhost/symphotest/assets/vendor/js/require.min.js:56:31
newContext/Module.prototype.emit#http://localhost/symphotest/assets/vendor/js/require.min.js:1189:17
newContext/Module.prototype.check#http://localhost/symphotest/assets/vendor/js/require.min.js:940:25
newContext/Module.prototype.enable#http://localhost/symphotest/assets/vendor/js/require.min.js:1177:17
newContext/Module.prototype.init#http://localhost/symphotest/assets/vendor/js/require.min.js:783:21
callGetModule#http://localhost/symphotest/assets/vendor/js/require.min.js:1204:17
newContext/context.completeLoad#http://localhost/symphotest/assets/vendor/js/require.min.js:1604:1
newContext/context.onScriptLoad#http://localhost/symphotest/assets/vendor/js/require.min.js:1711:21
require.min.js:900:37
TypeError: pager is undefined
Stack trace:
#http://localhost/symphotest/assets/js/panel-main.js:65:5
newContext/context.execCb#http://localhost/symphotest/assets/vendor/js/require.min.js:1690:24
newContext/Module.prototype.check#http://localhost/symphotest/assets/vendor/js/require.min.js:865:43
newContext/Module.prototype.enable/</<#http://localhost/symphotest/assets/vendor/js/require.min.js:1140:29
bind/<#http://localhost/symphotest/assets/vendor/js/require.min.js:131:20
newContext/Module.prototype.emit/<#http://localhost/symphotest/assets/vendor/js/require.min.js:1190:21
each#http://localhost/symphotest/assets/vendor/js/require.min.js:56:31
newContext/Module.prototype.emit#http://localhost/symphotest/assets/vendor/js/require.min.js:1189:17
newContext/Module.prototype.check#http://localhost/symphotest/assets/vendor/js/require.min.js:940:25
newContext/Module.prototype.enable/</<#http://localhost/symphotest/assets/vendor/js/require.min.js:1140:29
bind/<#http://localhost/symphotest/assets/vendor/js/require.min.js:131:20
newContext/Module.prototype.emit/<#http://localhost/symphotest/assets/vendor/js/require.min.js:1190:21
each#http://localhost/symphotest/assets/vendor/js/require.min.js:56:31
newContext/Module.prototype.emit#http://localhost/symphotest/assets/vendor/js/require.min.js:1189:17
newContext/Module.prototype.check#http://localhost/symphotest/assets/vendor/js/require.min.js:940:25
newContext/Module.prototype.enable#http://localhost/symphotest/assets/vendor/js/require.min.js:1177:17
newContext/Module.prototype.init#http://localhost/symphotest/assets/vendor/js/require.min.js:783:21
callGetModule#http://localhost/symphotest/assets/vendor/js/require.min.js:1204:17
newContext/context.completeLoad#http://localhost/symphotest/assets/vendor/js/require.min.js:1604:1
newContext/context.onScriptLoad#http://localhost/symphotest/assets/vendor/js/require.min.js:1711:21
require.min.js:900:37
Furtermore The panelViewModel.js contains:
define(['ko','imageGroupsVm','compMessage'],function(ko,ImageGroupsVM,loginViewModel)
{
var image_groups=new ImageGroupsVM();
return {'imageGroups':image_groups};
});
And the ImageGroupsViewModel Contains:
define(['ko','jquery'],function(ko,$)
{
console.log(ko);
return function imageGroupsViewModel()
{
var self=this;
self.albums=ko.observableArray();
self.init=function()
{
self.albums([]);
self.fetchData();
}
self.fetchData=function()
{
console.log("Data Fetched");
};
function Album(data)
{
}
};
})
All the JS files that I have are: (note that tin vendor classes are the external libraries I load)

I managed to fix it by replacing the 'ko' with 'knockout' whenever is required.
More specifically on main (the file you include in data-main on your html)
The following line:
'ko':"http://knockoutjs.com/downloads/knockout-3.4.0.debug",
Changed into:
'knockout':"http://knockoutjs.com/downloads/knockout-3.4.0.debug",
I Included on shim:
'pager':['knockout'],
And the
define(['jquery','ko','pager','panelVm'],function($,ko,pager,panelVm)
Changed into
define(['jquery','knockout','pager','panelVm'],function($,ko,pager,panelVm)
Therefore my main is:
requirejs.config({
paths:{
'text':'../vendor/js/text.min',
'knockout':"https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min",
'pager':"../vendor/js/pager.min",
'jquery':"../vendor/js/jquery.min",
'boostrap':"../vendor/js/bootstrap.min",
'imageGroupsVm':'../js/viewModels/imageGroupsViewModel',
'panelVm':'../js/viewModels/panelViewModel',
'compMessage':'../js/components/message',
'extBooleanToggle':'../js/extenders/booleanToggle'
},
shim:{
'pager':['knockout'],
'bootstrap':['jquery'],
},
waitSeconds: 200,
});
define(['jquery','knockout','pager','panelVm'],function($,ko,pager,panelVm)
{
pager.extendWithPage(panelVm);
ko.applyBindings(panelVm);
pager.start();
});
Also on my other javascript files on my project that are loaded with require I changed the line:
define(['ko',...,'other_lib'],function(ko,....,other_lib)
With:
define(['knockout',...,'other_lib'],function(ko,....,other_lib)
Note:
I also changed theese lines on other main.js that I load with require on another pages:
'ko':"http://knockoutjs.com/downloads/knockout-3.4.0.debug",
Changed into:
'knockout':"http://knockoutjs.com/downloads/knockout-3.4.0.debug",
I did this in order to load all the modules I make by using require.

Related

Rollup bundle using exports instead of module.exports

I have a library I am bundling using rollup and this is a section from the rollup.config.js file:
export default {
input: `src/${libraryName}.ts`,
output: [
{ file: pkg.main, name: camelCase(libraryName), format: 'cjs', sourcemap: true },
{ file: pkg.module, format: 'es', sourcemap: true },
],
....
}
It generates two files dist/libname.umd.js and dist/libname.es5.js. I have confirmed from putting a console.log statement in both the files that using require('libname') loads the dist/libname.umd.js. However, the following line:
var x = require('libname').X
console.log(x) // This is undefined
prints undefined. So, I tried to edit the dist/libname.umd.js file manually and at the bottom of the file I saw:
exports.X = X;
with the overall variable X being bundled somewhere above in the file. I modified this to:
module.exports.X = X;
and then it seems to work. I am a bit new to node/js so I wasn't sure if it this is the way to be exporting modules, but on reading a blog post (http://www.hacksparrow.com/node-js-exports-vs-module-exports.html) it turns out both of them should be fine? I am still a bit unclear on this one though.
Also, when I simply did this:
console.log(require('libname')
it prints [Function: uniqSetWithForEach] and console.log(require('libname')()) prints [].
EDIT So for the time being, just so that I can continue my work I have modified rollup.config.ts to add an outro:
export default {
...
output: [
{ file: pkg.main, name: camelCase(libraryName), format: 'cjs',
sourcemap: true,
outro: 'module.exports = Object.assign({}, module.exports, exports)'
}
]
...
}
and this seems to do it for now, but I'm pretty sure it's not a clean solution.

How to configure Prism with Nuxt

How can I configure Prism to work with Nuxt? I added it as a vendor in the nuxt.config.js file:
// * Build configuration
build: {
// * You can extend webpack config here
vendor: ['axios', 'prismjs'],
extend(config, ctx) {
if (ctx.isServer) {
config.externals = [
nodeExternals({
whitelist: [/^vuetify/]
})
];
}
}
}
Then in my page in the script section I import it:
<script>
import Prism from'prismjs';
export default {
data() {
return {
post: {}
};
},
// more data...
How can I use it then? I've tried calling it in mounted but it doesn't work. No errors are returned but it doesn't change anything on site.
mounted() {
Prism.highlightAll();
}
Turned out to be working, just forgot about including css styles.

GitHub Electron: build menu in required file

I am seasoned in JavaScript, but very new to node and to Electron. I am trying to piece the technique together from code samples and what documentation I can find.
I would like to include my menu code in a separate file. The main code is in a file called renderer.js and the menu code in one called menu.js. A simple example:
// renderer.js
function doit() {
alert('hello');
}
module.exports.doit=doit; // Added
var q=require('./menu');
var q=require('./menu');
// menu.js
var template = [
{
label: 'Test',
submenu: [
{
label: 'Something',
click() {
doit();
}
}
]
}
];
const {remote} = require('electron');
const renderer=require('./renderer'); // Added
const {Menu, MenuItem} = remote;
const app=remote.app; // Addes
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
The menu is created, but when selecting the menu item, I get the message: Uncaught ReferenceError: doit is not defined.
I understand the meaning of the message, and clearly variables are not passed between the files.
How can I accomplish this?
Update: I have added some lines in the sample incorporate the accepted answer below. This now works.
Clearly I did not understand the meaning of require(). It strikes me as odd that each file can require the other. Anyway …
Thanks
If you wish to access symbols defined in one Node module from another you have to export them via module.exports:
// renderer.js
function doit() {
// ...
}
module.exports.doit = doit;
And load the module via require:
// menu.js
const { doit } = require('./renderer');
// OR: const doit = require('./renderer').doit;
var template = [
{
label: 'Test',
submenu: [
{
label: 'Something',
click() {
doit();
}
}
]
}
];
This and much more is covered in the Node API docs.
I am trying to solve the same challenge. Currently I am looking into this:
https://github.com/ragingwind/electron-menu-loader
He basically adds a property 'event' and replaces that with an event handler.

require js defining modules in html script tags

I am trying to define a module for the initual configuration options of my app inside an script tag in my html. but I get the following error:
Error: Module name "options" has not been loaded yet for context: _. Use require([]) http://requirejs.org/docs/errors.html#notloaded
here is the html:
<script src="Scripts/require.js" data-main="/Recruiter/temp-search/App/main"></script>
<script>
define('options',['jquery'],function($) {
return options = {
salesPhoneNumber : '#ConfigurationManager.AppSettings.Get("SalesPhoneNumber")',
saleInfoMessage : "To access Temp Search candidate details, please call our team on " + salesPhoneNumber,
subscriptionInfo : #Html.Raw(new JavaScriptSerializer().Serialize(Model.AccessInfo ?? null)),
questionProLink: src="#(Request.Url.Scheme)://www.questionpro.com/a/TakeSurvey?id=#(Model.IsRecCon ? AppSettings.SurveyRecConId : AppSettings.SurveyOthersId)&custom1=#Model.RecruiterEmail&custom2=#Model.RecruiterId",
surveyEnabled: '#AppSettings.FlexSurveyEnabled',
whatsNewUrl: '#AppSettings.UrlWhatsNew',
salesPhoneNumber:salesPhoneNumber,
showSaleInfo: '#ViewBag.ShowSaleInfo',
fileDownloadFailCookieName:'#AppSettings.FileDownloadFail',
urls: {
signInUrl: '#string.Format("https://{0}/recruiter/account/signIn", Url.RequestContext.HttpContext.Request.Url.Host)',
signInTempsHome: '/recruiter/temp-search/home',
signInTempsSearch: '/recruiter/temp-search/api/temps',
checkAvailabilityUrl: '/recruiter/temp-search/api/availability',
searchUrl: '/recruiter/temp-search/api/temps/search',
accesslimitUrl: '/recruiter/temp-search/api/ecruiters/accessinfo',
previewUrl: '/recruiter/temp-search/api/temps/preview'
},
elements: {
signInRegisterDialog: $("#signInRegisterDialog"),
noSubscriptionDialog: $("#noSubscriptionDialog"),
searchForm: $("#searchForm"),
searchKeywords: $("#Keywords"),
searchLocation: $("#Location"),
searchRadius: $("#Radius"),
searchSortBy: $("#sortBy"),
searchTemp: $("#Temporary"),
searchContract: $("#Contract"),
searchPayRateFrom: $("#PayRateFrom"),
searchPayRateTo: $("#PayRateTo"),
searchAvailability: $("#AvailabilityConfirmed"),
locationErrorMsg: $("#locationErrorMsg"),
checkAll: $(".checkAll"),
checkCandidate: $(".checkCandidate"),
availability: {
availabilityBtn: $("#availabilityBtn"),
availabilityDialog: $("#availabilityDialog"),
additionalInformation: $("#AdditionalInformation"),
jobPosition: $("#JobPosition"),
jobLocation: $("#JobLocation"),
payRate: $("#JobPayRateFrom"),
payRateTo: $("#JobPayRateTo"),
startOn: $("#StartOnDate"),
duration: $("#Duration"),
checkAvailabilityForm: $("#checkAvailabilityForm"),
availabilityLocation: $("#checkAvailabilityForm #JobLocation"),
candidateIds: $("#CandidateIds"),
tempJobId: $("#TempJobId"),
msgPanel: $("#msgPanel"),
msg: $(".msg"),
errorAvailability: $("#availabilityError"),
availabilityConfirmationDialog: $("#availabilityConfirmationDialog"),
infoBubbleMessage : $("#infoBubbleMessage"),
availabilityConfirmationMsg: $("#availabilityConfirmationDialog .msgDialog"),
downloadInfoLink : $("#downloadInfoLink")
},
preview: {
previewBtn: $('.previewBtn')
},
messagePanel: $("#messagePanel")
},
minWageRate : #Constants.Range.ApprenticeshipsPerHourMin,
authentication : #(Request.IsAuthenticated.ToString().ToLower()),
minDate: '#String.Format("{0:yyyy/MM/dd}", DateTime.Now)',
pageInfo: {
number: #Model.Results.PageNumber,
size: #Model.Results.PageSize,
resultsCount: #Model.TotalResultsCount
},
criteria : #Html.Raw(new JavaScriptSerializer().Serialize(Model.Criteria)),
remainingAccessLimit: #Model.AccessInfo.Remaining,
totalAccessLimit: #Model.AccessInfo.Limit,
availableCandidates: #Model.AvailableCandidates,
candidates: #Html.Raw(new JavaScriptSerializer().Serialize(Model.Results ?? Model.Results.ToJSON()))
};
})
</script>
The problem is not with the code you show in your question but with how you ask RequireJS to load your module. The error message you show happens when you do a require call of this form:
var foo = require('foo');
This kind of require call does not work unless foo is already loaded, and to ensure it is already loaded you can manually load it yourself, or you can have RequireJS do it for you. However, to get RequireJS to do it for you, you need to write your code in a certain way. If you want a module to use foo and you want to use the require above then, you should do:
define(function (require) {
var foo = require('foo');
...
});
Or if you need to use module and exports, the callback can be function (require, exports, module) {....
Also, you should perform the following operations in this order:
Load RequireJS.
Execute define('options', ....
Then and only then start loading your application.
This means removing data-main and using an explicit require call after define('options'.

YUI 2 in 3 locally

I am new to YUI and I want to load YUI 2 in 3 locally, not from CDN. I have pasted both 2 and 3 in same directory named Scripts. I am pasting my code below:
<script type="text/javascript" src="/Scripts/build-yui3/yui/yui-min.js"></script>
function showError(panelId) {
YUI({
groups: {
yui2: {
base: '/build-yui2/',
// If you have a combo service, you can configure that as well
// combine: true,
// comboBase: 'http://myserver.com/combo?',
// root: '/2in3/build/',
patterns: {
'yui2-': {
configFn: function(me) {
if(/-skin|reset|fonts|grids|base/.test(me.name)) {
me.type = 'css';
me.path = me.path.replace(/\.js/, '.css');
me.path = me.path.replace(/\/yui2-skin/, '/assets/skins/sam/yui2-skin');
}
}
}
}
}
}
}).use('dd-drag', 'yui2-container', function (Y) {
Y.one("#" + panelId).setStyle('display', null);
var YAHOO = Y.YUI2;
var config = {
close: true,
width: "300px",
fixedcenter: true,
modal: true
};
panel = new YAHOO.widget.Panel(panelId, config);
var keylistener = new YAHOO.util.KeyListener(
document, {
keys: 27
}, {
fn: panel.hide,
scope: panel,
correctScope: true
});
panel.cfg.queueProperty("keylisteners", keylistener);
panel.render();
});
}
But this is not working. Throwing error: "YAHOO is undefined". Please help. Thanks..
Add an onFailure: function (error) {} method to your YUI3 config object. The error it gives you will tell you which files didn't load properly. I'm guessing the base property needs to be a full path not a relative path. I've never used patterns so I'm not sure how to debug it.

Resources