How to load DyGraphs using require.js - javascript

I am trying to integrate DyGraph in a web site that uses require.js for loading modules.
It is possible to load DyGraph using require?
I looked at the code and did not see any define() in there.
I came across this project where it looks like it needs to be "wrapped".
https://github.com/mgmarino/kanso-dygraphs
Has anyone done this before?
Thanks.

The latest dygraphs was fine to load with just:
// put this in your require config
paths: {
'dygraphs' : 'bower_modules/dygraphs/dygraph-combined',
}
...
require('dygraphs');
console.log(Dygraph); // Dygraph is added to global scope

Related

How to call a JS function at the page load of Docusaurus site?

I need to load a custom JS function I wrote at the beginning of the page load in a Docusaurus documentation site.
What have I tried so far?
Attempt #1: Appending the script to the index.js file (.\src\components\HomepageFeatures\index.js)
This attempt worked well during testing but then yarn was not able to build the project anymore. The error was as follows:
[ERROR] Docusaurus server-side rendering could not render static page
with path /. [INFO] It looks like you are using code that should run
on the client-side only. To get around it, try using <BrowserOnly>
(https://docusaurus.io/docs/docusaurus-core/#browseronly) or
ExecutionEnvironment
(https://docusaurus.io/docs/docusaurus-core/#executionenvironment). It
might also require to wrap your client code in useEffect hook and/or
import a third-party library dynamically (if any).
Attempt #2: To counter the issue presented during my first attempt, I created a separate (.js) file in (./src/js/myfunction.js) and then tried to load that file. To keep this question short, I will add a sample script below to showcase the issue:
import BrowserOnly from '#docusaurus/BrowserOnly';
<BrowserOnly>
window.onload = function() {
alert("Welcome!");
}
</BrowserOnly>
Then I went to the Docusaurus config file and added the following:
scripts: [
{
src: './src/js/myfunction.js',
async: false,
},
],
The site was built successfully this time, but the function was not getting loaded. I tried to call the function as well but still, I was getting nothing. I think I don't understand how the <BrowserOnly> feature works or I am missing something else.
Your help will be much appreciated!
I solved the issue eventually by adjusting the custom-made JS file as follows:
import ExecutionEnvironment from '#docusaurus/ExecutionEnvironment';
if (ExecutionEnvironment.canUseDOM) {
// My own custom JS code.
}
Thereafter, I loaded that custom JS file from the config file (docusaurus.config.js) by adding the following:
clientModules: [
require.resolve('./path-to-custom-code/custom-code.js'),
],
This has been mentioned briefly in the documentation but it wasn't clear at all. The documentation of Docusaurus requires more elaboration and examples.
You can view it here though:
https://docusaurus.io/docs/advanced/client#client-modules
If anyone has a better approach, please add it to this post. Thanks!

Uncaught ReferenceError: define is not defined typescript

I am new to typescript, knockout and requirejs. I have created some demo using this files. Now, I want to implement some minor logic using typescript and knockoutjs.
I have created 4-5 typescript files, which are imported internally. When I run the html file. I am getting the error stating. as Titled
Can somebody help me on this error. What I am missing in this code.
have search on google and spend quite a good time but didn't find the proper solutions. It must be related to requireJS to define all modules. But, as new in requireJS not able to catch up with that. I have also search stackoverflow for the similar error, but it doesn't help me out.
Waiting for the solution
Here your TypeScript has compiled happily, to code that will work in a requireJS environment (technically, an AMD environment). That means it generates output that assumes that define/require etc all already exist.
The overall answer is that you need to include RequireJS before you depend on your compiled code.
Notably the error suggests you've made a separate mistake though: you're depending directly on the RequireJS module scripts (i.e. you have a <script src="my-compiled-code.js"></script> tag in your HTML). That's not how require modules work. Instead, once you've made RequireJS available, you should have a single top-level startup script (either inline in your HTML or as a separate file) that configures RequireJS and then require()'s the top-level files of your application to start everything off. You can load this file either by hand, or with RequireJS's "data-main" attribute.
For example, a minimal HTML looks something like:
<!DOCTYPE html>
<html>
<head>
<script data-main="scripts/main" src="scripts/require.js"></script>
</head>
<body>
</body>
</html>
This loads RequireJS from 'scripts/require.js' and then tells it to load the script at 'scripts/main.js' to start off the loading process (you'll probably want to update both paths - note that data-main doesn't need a .js extension).
The main script should then be something very simple like:
// Set up any config you need (you might not need this)
requirejs.config({
basePath: "/scripts"
});
// Tell RequireJS to load your main module (and its dependencies)
require("mainmodule");
Generally, it's not TypeScript problems you're fighting here, it's RequireJS. I'd try spending a bit more time playing with just Require (maybe in pure JavaScript, so it's clearer) and looking at working examples for that, so you can get that bit working first, then add in the rest.

Using require js with angular js

I'm trying to use require js and angular js together. Referred to someone guides by googling:
http://marcoslin.github.io/angularAMD/#/home
http://www.sitepoint.com/using-requirejs-angularjs-applications/
Both guides seem to use angular, and angular-route and angular-amd, but I thought they were for other complicated purposes, so I only used "angular js" (so there is no shim in require.config()).
My main.js looks like this;
require.config({
paths: {
jquery : 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min',
'angular' : 'https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min',
'class' : 'class',
'utility' : '../utility/utility',
},
deps: ['main1']
});
where deps: ['main1'] is the file to load right after require is defined as the first guide uses.
But I'm keep getting this error:
Error: $injector:modulerr
('UpdateApp' is the name of the app that I'm using in my project.)
And the webpage says that I get the error when I've forgotten to include the file with the defined module.
Not using deps: ['main1'] but using require(['angular'], function(){} and logging out angular.module('myApp',[]) logs Object nicely though. ... It seems like require(['angular'], function(angular) does not work but require(['angular'], function() works for me, and guides don't seem to tell me whether I should do the latter or the former.
I thought it would be as simple as adding angular js in paths, and loading it with require() or define() will work, but it's not...
How do I use Require JS and Angular JS as simple as just using them together to print "hello world"?
Looking into your code, I can see that you clearly mis-understood about the concept of using requireJS and angular together. Either of the links you found are make by expert JS developers. Where both tried to combine angular and requireJS as simple as it could. So you need to accept the fact that it is complicated.
=> This is why I will not try to help you with some code. Because it will took lots of time and it will related with many topic which will not likely fit into a single question and answer on stackoverflow.
How do I use Require JS and Angular JS as simple as just using them together to print "hello world"?
At first I want to repeat it. This is nothing like simple work. For requireJS you need to at least have advanced knowledge about what called AMD and able to imagine how things happen asynchronusly when requireJS trying to load an JS library.
Secondly, common knowledge about angular module/service injeaction. Since both requireJS and angular can do some sort of module/service injection you need to know about the difference between these two.
Third, the initial stage of your webapp. Since both requireJS and angular need to be initialled to run properly. So this will also the requirement.
Sum up
You will NOT able to understand both in a day or two. It will take time. But fortunately I have a couple of suggestions for you.
Research some about how requireJS and angular load their depenencies.
Go for angularAMD get the project seed. Set it up, run it, play with it.
Improve your knowledge about the initial state of both.
...
Profit!
P.S. just FYI. An year ago, I started with requireJS and angular. And I got hitted up with a big wall of knowleges, just like you. And these are what I have tried to understand them. Take your time, it is not like using jquery which can learn in a day or two. Even for some JS expert it took months just for them to confident about angular (not counting combine it with requireJS). Cheers!
Inside your main1.js you must be use require(['angular'], function(){} to start your application.
Require JS will give you a package dependency manager, concatenator/uglifier, javascript file loader, and an injector. Require JS injectors are used for injecting classes versus Angular, which is used to inject instances.
The big advantage is that RequireJS is going to speed up your application by managing your load and runtime dependencies. It's useful for big SPA's.
You can set up your file structure by defining all of your dependencies using "define". For functions to execute, you will need to use "require".
Here is a helpful video:
https://www.youtube.com/watch?v=4yulGISBF8w&index=1&list=PLgVbnDyASc1qDAam3Fe0f-u6u9MYL6pC8

How do you use a page's existing jQuery + Twitter Bootstrap/plugins with StealJS?

I have a project that uses Twitter Bootstrap 3, however, I am supplementing the existing javascript situation with a CanJS app. For CanJS dependency management I chose their package StealJS. However, it appears that no matter what I do, StealJS insists on loading jQuery again, overwriting $.fn, of course.
In this question a core contributor answers that the solution is to "steal" a blank.js file. However, this breaks steal/build for production as can/util/jquery/jquery.js is passed 'jquery' as undefined (the results of blank.js).
I have tried variations on StealJS's stealconfig.js settings including map, paths, and completed but nothing seems to work.
Here is an example of doing this in RequireJS. Is the solution simply not to use StealJS and to use RequireJS instead?
You can try a solution that is similar to the RequieJS solution you linked to. That is, create a dummy file that looks like this:
steal(function(){
return window.jQuery;
});
And in stealconfig.js map jquery to wherever you put this file.

Using RequireJS with legacy code

I'm working with a very large project that uses:
Legacy JSP pages that includes javascript files with script tags
Backbone models and views that uses other javascript modules without RequireJS
We now want to start using RequireJS with jQuery, BackboneJS and UnderscoreJS for everything we develop from now on, but we don't have the resources to rewrite all the legacy JSP pages. We may have time to rewrite the Backbone models and views we have already developed.
The problem is that for our legacy code (both 1 and 2 above) we include all our javascript files in a huge file and ship to the browsers. This huge file must be able to co-exist with our new RequireJS templates, but how can I e.g. separate certain parts of the huge file, so I can use them with the templates using RequireJS? Without having to rewrite all pages that uses this part of the file, or having duplicate code.
Thanks!
I don't know if I fully grasp the problem at hand, but I think a the shim or map functions of RequireJS will help you out.
Extract the parts you want in a new module from your huge javascript file. Then tell RequireJS that your huge javascript file is a dependecy for this new module using shim. Something like:
requirejs.config({
shim: {
'new-module': {
deps: ['huge-javascript-file'],
exports: 'NewModule'
}
});
Shim documentation: http://requirejs.org/docs/api.html#config-shim
The map function might be useful when only portions of your new code have to use your old huge file. Check out this documentation: http://requirejs.org/docs/api.html#config-map
I don't think there is One True Way to achieve this, but I've approached a similar problem by defining module "facades" around the globally scoped code. Let's say your legacy scripts define a global variable called foo. You can define a AMD module and export that variable from it:
//foo.js
define(function() {
return window.foo;
});
//bar.js
define(['foo'], function(foo) {
//do something with foo
});
This way you only need to write a single-line facade every time you need to use a new piece of the existing, globally defined code, without breaking existing code which expects the same code to be globally defined. Over time you can move and refactor the actual implementation into the module without breaking consumer code.

Categories