How to inject external JS library into a module? - seedstack

I'm using SeedStack to create a web application. In order to do that, I use W20 to develop my frontend. I need specific JavaScript libraries into that project. How can I inject an external javascript library into it ? I want to use Chart.js http://www.chartjs.org/ to visualize data into charts. To do that, I suppose that I have to inject ChartJS as a dependency module in Angular.
Thank you for your help.

Before getting to the specific answer, please note that SeedStack already has an add-on for charts. As for integrating a library with W20, you have two main things to do:
Configure RequireJS to load the JS file and be able to inject it as a dependency.
Integrate the library with the AngularJS framework, which is often done by writing some directive.
Fortunately for you, Angular directives are already available for Chart.js, thanks to the angular-chart.js library. You just need to configure RequireJS to load it. Add a requireConfig section to the manifest of one of your fragments:
{
"id": "my-fragment",
...
"requireConfig": {
"paths": {
"{angular-chart.js}": "${components-path:bower_components}/angular-chart.js/dist",
"{chart.js}": "${components-path:bower_components}/chart.js/dist"
},
"map": {
"{angular-chart.js}/angular-chart": {
"angular": "{angular}/angular",
"chart": "{chart.js}/Chart"
}
}
}
}
The paths section declares locations of the two Chart.js libraries. Note that we use a variable named components-path with a default value of bower_components here. This is useful when using the W20 bridge add-on.
The map section declares a mapping between the expected and the real paths for dependencies of angular-chart.js.
You can then use the angular-chart.js library according to its documentation:
define([
'{angular}/angular',
'{angular-chart.js}/angular-chart',
], function(angular) {
var module = angular.module('myModule', ['ngResource', 'chart.js']);
module.controller('ContentController', [ '$scope', function($scope) {
// your JS code here
// (with your markup in a corresponding angular template)
}]);
});

Related

Vue.js including non-npm JavaScript library

I'm a total beginner with Vue.js and struggling to find the answer to what I feel is a fairly basic need.
I have a JavaScript library that cannot be installed locally and must be imported via script tag in the index.html file in the old-fashioned way:
<script src="https://foo.bar/scriptyscripts.js"></script>
This library has a bunch of methods in it that I need to use in various spots throughout my app, so it's not going to be a problem to load it globally. The issue I'm facing is that it's loading fine, but the methods are not being recognised in components.
I can use the methods and whatnot if I put them all in a script tag in the index.html however doing that rather defeats the whole point of having components.
Can anyone help me with the step that I'm missing to register all of the methods in this loaded js file so my components don't get mad?
Specifically, the script contains require.js and a collection of other things including JQuery.
Including the library makes the method 'require' available, which is used to load other modules on demand - the example being "js/qlik" in the below snippet. "js/qlik" loads JQuery and a stack of stuff associated with "qlik".
//async login method here. not relevant to this problem
login().then(() => {
require.config({
baseUrl:
(config.isSecure ? "https://" : "http://") +
config.host +
(config.port ? ":" + config.port : "") +
config.prefix +
"resources",
webIntegrationId: config.webIntegrationId,
});
//Load js/qlik after authentication is successful
require(["js/qlik"], function (qlik) {
qlik.on("error", function (error) {
$("#popupText").append(error.message + "<br>");
$("#popup").fadeIn(1000);
});
$("#closePopup").click(function () {
$("#popup").hide();
});
var app = qlik.openApp("caa866be-c8e1-44c8-b67b-dac9d24421fa", config);
});
});
The problem I have is that if I load this library in the index.html file and then try to execute the methods in the snippet above in any component, it does not know that the methods are available.
I see:
'Module not found: Error: Can't resolve 'js/qlik'
66:11 error '$' is not defined
which indicates that the components are unaware of the methods because they're not registered like they would be if I were importing a packaged afterinstalling it locally via NPM
i.e. Your original js code: function abc(){// sth...}
What you need: window.abc = ()=>{// sth...}
Even if you want it in Vue dom.
You should add vue.prototype.abc = ()=>{//sth...}

Translations Service

I'm looking for a solution/idea to dynamically change the translation value of each key in Sparatcus translations files outside the code. I don't want only to create a file and override the I18nModule config, I'm looking for some kind of service/API like Lokalize API to be able to change the translation values outside the code.
Thanks in advance!
The internationalisation features are prepared for this. Although we do not have a service at hand for the localised labels, Spartacus is prepared for this. You can read more about this at https://sap.github.io/spartacus-docs/i18n/#lazy-loading. You can configure loadPath to an API endpoint, including the variable language (lng) and namespace (ns).
imports: [
B2cStorefrontModule.withConfig({
i18n: {
backend: {
loadPath: 'assets/i18n-assets/{{lng}}/{{ns}}.json'
// crossOrigin: true (use this option when i18n assets come from a different domain)
},
chunks: translationChunksConfig
}
})
];

Multiple Aurelia Instances - Aurelia Webpack Plugin - aureliaApp option - "module not found"

I am composing my web app as a number of Aurelia "feature" apps - although I'm not using Aurelia features as such. Consequently in my html markup I have two entry points pointing to different apps:
<!-- Top Navigation Bar -->
<div aurelia-app="topnav"></div>
<!-- Main App-->
<div aurelia-app="main"></div>
I am using webpack and everything works perfectly using the single "main" app. Webpack generates a JS file "main.bundle.js" which I include in the src tag.
Things are not so straightforward when I added the "topnav" app. In webpack I tell the plugin to use a different aureliaApp name:
new AureliaPlugin({ aureliaApp: "topnav"}),
and, as you can see my HTML entrypoint also calls "topnav". Webpack generates a JS file "topnav.bundle.js" which I also include. I have a file called "topnav.ts" which contains the aurelia Cionfigure function which ends:
aurelia.start().then(() => aurelia.setRoot(PLATFORM.moduleName("nav")));
And a pair of files "nav.ts", "nav.html" which constitute my viewmodel and view.
When I run the app aurelia loads and the "nav" module code executes. But I then get an error - see below.
The module which it reports that it cannot find is the one entered into the HTML markup.
Should this work? Have I missed something?
I should add, everything seems to work. I can create and update properties in the viewmodel and these are bound to the view. It's just that this error is thrown.
You are doing nothing wrong, just unsupported scenario. Per official doc-wiki: https://github.com/aurelia/webpack-plugin/wiki/AureliaPlugin-options#aureliaapp
You can have only 1 auto entry module with aureliaApp configuration. To solve this, you just need to add PLATFORM.moduleName('topnav') to your main.ts (and put it on root level)
Another way to do is to bootstrap manually:
// in your index.ts
import { bootstrap } from 'aurelia-bootstrapper';
// bootstrap top nav application, with one instance of Aurelia
bootstrap(aurelia => {
// do your configuration
aurelia
.start()
.then(() => aurelia.setRoot(
PLATFORM.moduleName('topnav'),
document.querySelector('#topnav')
);
});
// bootstrap main application, with another instance of Aurelia
bootstrap(aurelia => {
// aurelia.use.standardConfiguration();
// ...
aurelia
.start()
.then(() => aurelia.setRoot(
PLATFORM.moduleName('app'),
document.querySelector('app')
)
});

RquireJS with Module in TypeScript

I'm studing TypeScript and RequireJS.
I want to simple module require but module type information missing.
Is there smart solution in such situation?
requirejs(['backbone'], (Backbone) => {
// In this function.
// Backbone is 'any'
});
requirejs(['backbone'], (BackboneRef: Backbone) => {
// error : Type reference cannot refer to container
// 型参照でコンテナー 'Backbone' を参照できません。
});
To do so you need to do the following:
Download backbone.d.ts from https://github.com/borisyankov/DefinitelyTyped, the backbone.d.ts provides typescript strongly-typed interface, if you use IDE like Visual Studio, you can have all the intellisense support to Backbone
(Optional) Config backbone in RequireJS
In your TypeScript class, you can reference Backbone like the following
`
/// <amd-dependency path="backbone" />;
/// <reference path="path/to//backbone.d.ts" />;
export class YourModel extends Backbone.Model {
}
The amd-dependency tells the compiler how to reference backbone, so it would generate the correct define statement in JavaScript.
The reference provides a way to Backbone's definition for typed check.
Hope this helps! TypeScript eliminates the hell of writing long define or require js statement, which can be error-prone in situation where there are lots of dependencies.

Simply cannot make SignalR (asp.net mvc4) and require.js work together

I've seen similar posts around the web and nothing anyone has suggested works for me. I'm really faced with the choice of dumping one or the other it seems at this point.
This "Getting Started with SignalR and MVC 4 tutorial":
http://www.asp.net/signalr/overview/getting-started/tutorial-getting-started-with-signalr-and-mvc-4
says you need two script includes to make signalR work:
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-1.0.1.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
I'm at a loss as to how to make the second one, the autogenerated SignalR hub script, happen in require.js. Unless I'm missing something there just doesn't seem to be a viable require.js syntax for inclusion of autogenerated scripts. Without it you get this error at line 159 of jquery.signalR-1.1.2.js:
"JavaScript runtime error: SignalR: Error loading hubs. Ensure your hubs reference is correct, e.g. "
The code at that point in jquery.signalR is doing this:
signalR.hub = {
start: function () {
// This will get replaced with the real hub connection start method when hubs is referenced correctly
throw new Error("SignalR: Error loading hubs. Ensure your hubs reference is correct, e.g. <script src='/signalr/hubs'></script>.");
}
};
Has anyone actually made this autogenerated script thing happen via require.js?
Been studying this a bit more. Let me add some detail:
I'm using this approach - Structuring scalable client side applications: (http://johndavidmathis.wordpress.com/2013/04/23/structuring-scalable-client-side-applications/) to make a more scalable structure. Second part in that series "Permit modules to utilize multiple files and a logical folder structure" http://johndavidmathis.wordpress.com/2013/04/23/structuring-scalable-client-side-applications/ has me splitting my actual signalr code out into a separate Marionette chat module (separate from my main app.js file) to achieve a better file structure. I really like this approach. The rest of my project is set up like this now and it really is showing benefits when it comes to finding code. I think that extra split is where I'm stuck. Can't seem to get that second dependency, the autogenerated script, into that separate chat module file. I'm still studying this but it looks like this to me at this point. require.js gets the dependency into my Marionette app:
require(["marionette","handlebars", "signalr", "signalr.hubs"], function (Marionette) {
window.App = new Marionette.Application();
App.addRegions({
headerRegion: "#header",
contentRegion: "#content",
footerRegion: "#footer",
});
require(["modules/main/loader", "modules/chat/loader"], function () {
App.start();
});
})
If I want chat that dependency to make its way further into the app, into the chat module in another file?
Something like?
define(dependencies,
function () {
App.module("ChatModule", function (ChatModule, App, Backbone, Marionette, $, _, "signalr.hubs", "signalr.hubs") {
// SignalR Proxy created on the fly
var chat = $.connection.chatHub;
// Start the connection
$.connection.hub.start();
//more chat code...
An update:
The answer below does work in my dev environment. But it does not work when I publish the code to a real production server.
When the code is published to a real production server (IIS 6.1 on Windows Server Enterprise 2008 R2) the browser console once again shows a "404" for the autogenerated reference.
Specifically, the console shows the "?" is being added into the reference path before ".js", like this...
http://mydomain.com/myapp/Scripts/application/signalr/hubs?.js...
Tried taking the "?" out but then it removes my app name from the path, like this...
http://mydomain.com/signalr/hubs.js.
I think what would get me there is the first one, without the "?", like...
http://mydomain.com/myapp/Scripts/application/signalr/hubs.js
I'm just not seeing how to make that happen.
FINAL UPDATE:
Final piece of the puzzle for production server is the site's virtual directory. Here's final code that worked for me. Thanks Raciel R for your help:
requirejs.config({
paths: {
//core
"jquery": "jquery-1.9.1",
"signalr": "jquery.signalR-1.1.2",
"signalr.hubs": "/productionservervirtualdirectory/signalr/hubs?"
},
shim: {
"jquery": {exports: "$"},
"signalr": { deps: ["jquery"] },
"signalr.hubs": { deps: ["signalr"] }
});
//Then all you have to do is to make signalr.hubs required in your modules. Ie:
require(["signalr.hubs"], function(){
//your code here
});
requirejs.config({
paths: {
//core
"jquery": "jquery-1.9.1",
"signalr": "jquery.signalR-1.1.2",
"signalr.hubs": "/signalr/hubs?"
},
shim: {
"jquery": {exports: "$"},
"signalr": { deps: ["jquery"] },
"signalr.hubs": { deps: ["signalr"] }
});
Then all you have to do is to make signalr.hubs required in your modules. Ie:
require(["signalr.hubs"], function(){
//your code here
});
I set up RequireJS successfully using #raciel-r's solution but I was still having problems with other JavaScript modules like karma that were also confused by the dynamic proxy. I converted the signalr proxy to a static file and used that with RequireJS instead:
Import Microsoft.AspNet.SignalR.Utils
Run packages/Microsoft.AspNet.SignalR.Utils.2.X.X/tools/signalr.exe
ghp /path:my/bin /o:path/to/scripts/server.js where /my/bin is the directory containing the assemblies with your SignalR Hubs.
Replace your reference in to /signalr/hubs with server:
requirejs.config({
paths: {
// ...
"signalr.hubs": "path/to/scripts/server"
},
// ....
If you are using the convenience methods of the generated proxy, you will also have to rewrite them (see How to create a physical file for the SignalR generated proxy)