Dynamic loading of modules and components at runtime in Angular 4 - javascript

I've been looking to develop a method for loading modules and/or components into an AOT-compiled Angular 4 application and been stymied by a variety of solutions that never quite seem to get me where I want to be.
My requirements are as such:
My main application is AOT compiled, and has no knowledge of what it is loading until runtime, so I cannot specifically identify my dynamic module as an entry component at compile time (which is explicitly necessary for the 'dynamic' component loading example presented on Angular.io)
I'd ideally love to be able to pull the code from a back end database via a GET request, but I can survive it simply living in a folder alongside the compiled site.
I'm using Webpack to compile my main application, breaking it into chunks - and so a lot of the SystemJS based solutions seem like dead ends - based on my current research, I could be wrong about this.
I don't need to know or have access to any components of my main application directly - in essence, I'd be loading one angular app into another, with the dynamically loaded module only perhaps having a few tightly controlled explicit interface points with the parent application.
I've explored using tools like SystemJsNgModuleLoader - which seems to require that I have the Angular compiler present, which I'm happy to do if AOT somehow allowed me to include it even if I'm not using it elsewhere. I've also looked into directly compiling my dynamic module using ngc and loading the resulting ngfactory and compiled component/module, but I'm not clear if this is at all possible or if so - what tools Angular makes available to do so. I have also seen references to ANALYZE_FOR_ENTRY_COMPONENTS - but can't clearly dig up what the limitations of this are, as first analysis indicates its not quite what I'm looking for either.
I had assumed I might be able to define a common interface and then simply make a get request to bring my dynamic component into my application - but Angular seems painfully allergic to anything I try to do short of stepping outside of it alltogether and trying to attach non-angular code to the DOM directly.
Is what I'm trying to do even possible? Does Angular 2+ simply despise this kind of on the fly modification of its internal application architecture?

I think I found an article that describes exactly what you are trying to do. In short you need to take over the bootstrap lifecycle.
The magic is in this snippet here.
import {AComponentNgFactory, BComponentNgFactory} from './components.ngfactory.ts';
#NgModule({
imports: [BrowserModule],
declarations: [AComponent, BComponent]
})
export class AppModule {
ngDoBootstrap(app) {
fetch('url/to/fetch/component/name')
.then((name)=>{ this.bootstrapRootComponent(app, name)});
}
bootstrapRootComponent(app, name) {
const options = {
'a-comp': AComponentNgFactory,
'b-comp': BComponentNgFactory
};
https://blog.angularindepth.com/how-to-manually-bootstrap-an-angular-application-9a36ccf86429

Related

Using stickit with Backbone in Webpack

I'm migrating my code from 'vanilla' to WebPack. Previously the backbone.js and backbone.stickit.js were loaded in index.html so that the code that was running later has seen stickit() function under Backbone.View.prototype (which is what my views extend from.
However, after migrating to WebPack I've started getting errors, that this.stickit() is not defined, which I've get rid of via adding the require to every JS file defining views extending from Backbone.View:
import Backbone from 'backbone';
require('backbone.stickit/backbone.stickit');
I don't feel good about that solution. In that specific case it is not so bad becasue my views explicitely use stickit. However, there are modules and extensions that alter the default behaviour, and I'd like to define them in one place.
How should I go about handling it? I've got a concept of importing Backbone, applying all plugins, and re-exporting it:
import Backbone from 'backbone';
require('backbone.stickit/backbone.stickit');
....
const Backbone2 = Backbone;
export {Backbone2};
which looks a bit too tricky...
How should I go about it? Shouldn't the webpack layer contain only one copy of Backbone after build, no matter in how many places it was imported, and which plugins were required?

dynamically load modules in Meteor node.js

I'm trying to load multiple modules on the fly via chokidar (watchdog) using Meteor 1.6 beta, however after doing extensive research on the matter I just can't seem to get it to work.
From what I gather require by design will not take in anything other than static strings, i.e.
require("test/string/here")
Since if I try:
var path = "test/string/here"
require(path)
I just get Error: Cannot find module, even though the strings are identical.
Now the thing is I'm uncertain how to go on about this, am I really forced to either use import or static strings when using meteor or is there some workaround this?
watchdog(cmddir, (dir) => {
match = "." + regex_cmd.exec(dir);
match = dir;
loader.emit("loadcommand", match)
});
loader.on('loadcommand', (file) => {
require(file);
});
There is something intrinsically weird in what you describe.
chokidar is used to watch actual files and folders.
But Meteor compiles and bundles your code, resulting in an app folder after build that is totally different from your project structure.
Although Meteor now supports dynamic imports, the mechanism is internal to Meteor and does not rely on your actual project files, but on Meteor built ones.
If you want to dynamically require files like in Node, including with dynamically generated module path, you should avoid import and require statements, which are automatically replaced by Meteor built-in import mechanism. Instead you would have to make up your own loading function, taking care of the fact that your app built folder is different from your project folder.
That may work for example if your server is watching files and/or folders in a static location, different from where your app will be running.
In the end, I feel this is a sort of XY problem: you have not described your objective in the first place, and the above issue is trying to solve a weird solution that does not seem to fit how Meteor works, hence which may not be the most appropriate solution for your implicit objective.
#Sashko does a great job of explaining Meteor's dynamic imports here. There are also docs
A dynamic import is a function that returns a promise instead of just importing statically at build time. Example:
import('./component').then((MyComponent) => {
render(MyComponent);
});
The promise runs once the module has been loaded. If you try to load the module repeatedly then it only gets loaded once and is immediately available on subsequent requests.
afaict you can use a variable for the string to import.

AngularJS module architecture

I am planning to create several modules in my company's application and I'm having trouble designing the architecture for the modules. I have done research and it seems like either you are supposed to use one module per page, or create a 'master' module that depends on all of your other modules. I don't like this approach because it means I have to load all of the javascript for every aspect of my application for every single page. That seems inherently wrong, but I also can't seem to figure out how to handle it the other way if I need to use one module in multiple places on a page. For example, I have a membership module that I have and I'm attaching to the header section of my web page. This would be intended for logging in, registration, and performing a 'forgot password' type workflow.
On another page dedicated to changing a password (from a reset link) the header is also present, but I want to include the password reset functionality in the membership module. I've read that one methodology of designing your application is by functionality/feature. I figured membership was an appropriate application of that, but now I'm not sure since I am having trouble applying the membership module more than once on any particular page.
Am I on the right track, or is there a preferred method for this? Should I have a separate module for the header and one for the rest of the page? Should I just bite the bullet and load everything? (I hope not...)
I should also note that this is an ASP.Net MVC application where we are still heavily relying on MVC for serving views and partial views. As such I wanted to use a render javascript section to dynamically load only the javascript necessary for that page to function. Is this a farce?
<header ng-app="membership">
//stuff for header membership functions
</header>
<div ng-app="membership">
//somewhere else that needs membership, outside of header
</div>
I personally like Mini SPAs (Silos) instead of full SPA. You can watch Miguel A Castro's video, and download the source at his website.
What it does is when a request comes in, it goes to ASP.Net MVC Route first. Then, Angular Route takes over the rest. It is a very slick design.
FYI: Angular 2 is right around the corner, so I went ahead and updated those to Angular 1.5 Compotent so that I can convert to Angular 2 easily later.
If you want, you can stop there. I went one step future, and use Strongly Typed Views using Matt Honeycutt's Building Strongly-typed AngularJS Apps with ASP.NET MVC 5 approach.
Then I implemented Angular Helpers like Axel Zarate's ANGULAR.NET – HELPERS FOR ASP .NET MVC 4.
On an Angular application, as it is a Single Page Application, yes, all your javascript must be loaded. It's the code of your application and it's necessary. That's done only once on first page load.
You're always on the same page, but on a different state.
One good approach is to define a master module who include all other modules. Those modules can also include other "sub modules" they need.
angular.module('App', [
'App.Membership'
// ...
// All others modules you need, including 3rd party modules
])
Then, on each module, you can define the different states associated and their controller
angular.module('App.Membership', [
// Module dependencies
])
.config(['$stateProvider', function($stateProvider) {
//State definition
$stateProvider.state('membership', {
parent: 'app',
url: '/member',
controller: 'MembershipCtrl',
template: '<ui-view/>'
});
}]);
You can also add a global controller to handle elements who are always present, like a header.
Hope this helps

Generate components in sub-folders in ember/ember-cli

Based on recommendations for the preparation for Ember 2.0...
• In general, replace views + controllers with components
• Only use controllers at the route level...
...we're supposed to eschew Controllers and Views in favor of Components. I haven't been able to figure out and/or understand how to generate Components that aren't direct parents of the components folder, i.e. components/component-name.js.
My current controllers folder looks something like:
/controllers
/account
index.js
edit.js
/business
index.js
Basically, there are sub-folders that group logic based on the sections of the application. How do I accomplish this with just components?
Seeing that components must have a "-" in them, I tried, but get an error...
ember generate component account/index-module.js
You specified "account/index-module.js", but due to a bug in Handlebars (< 2.0) slashes within components/helpers are not allowed.
Do all components have to be like
components
account-index.js
account-new.js
business-index.js
i.e. all in the same folder? This will start to get out of hand with the addition of what I actually consider to be components (things like video-viewer.js, text-editor.js, radio-button.js).
I would really like to have components in sub-folders, but unsure how to do this.
components
/media
/audio
audio-player.js
/video
video-player.js
/text-editing
text-editor.js
editor-toolbar.js
My components folder is already gross and I just got started:
Is it okay to leave the account/business logic in Controllers (seeing that it does say you should only use controllers at the Route level)?
I'm really confused about this "all components, all the time" convention.
Ok, so I had the same problem and as of ember 1.9-beta.3 (that's the version I tested). It is possible to have components nested under resource directories.
That means that you can have a "user" route or resource. And let's say you have a component which you only want to use with the user resource, so you want to put the component under the resource directory.
The way to do it is to put the component under the resource directory app/pods/user/component-name/template.hbs. The important part is to remember that components must have a dash in their name. It can't be just .../user/component it has to be .../user/component-name with a dash. Then you can use the component as {{user/component-name}} in your templates.
Also I think this is only possible when you're using the pod structure.
Ok, I think this question/answer needs a bit of an update for 2019. I have been using Ember for all of about a month, and my components folder has already become a pigpen. And the tutorial and main API docs don't really cover how to organize your components.
So I did a search of course. And the only answers I could find (like this one) are from around 2014-2015, and don't reflect modern Ember. I was about to accept my fate when I found this in the Ember syntax conversion guide.
(Note to the Ember folks: This is an important issue, one that almost every new user will encounter. It should feature a bit more prominently in the documentation. Maybe not the tutorial, but definitely in Components section)
You can in fact generate components under a sub-folder in Ember as such:
$ ember generate component foo/bar-baz
installing component
create app/components/foo/bar-baz.js
create app/templates/components/foo/bar-baz.hbs
installing component-test
create tests/integration/components/foo/bar-baz-test.js
So that's great, the files are created under components/foo and templates/components/foo. And to resolve the name of the component for use in another template, you can use either the old style syntax:
{{foo/bar-baz }}
Or the new style angle bracket syntax:
<Foo::BarBaz />
As the assertion suggests this is due to Handlebars 1.x, and will be available soon.
Ember 1.9 beta builds currently support this, though I'm not positive if ember-cli's resolver would work with it right now. You can read more about Handlebars 2.0 here.
Using a pods structure will also help with organization, and I believe is going to be the recommended strategy going forward.
For now, I'd suggest not to worry about it! Remember the transition plan will be smooth, and as the official releases come out for Ember and Ember CLI, you'll get deprecation warnings.

Using require.js for client side dependancies in Adobe CQ5

I was wondering if anyone had experience using require.js with the Adobe CQ5 platform. I'm writing a Chaplin.js(backbone-based) single page app that will be integrated into the rest of CQ5-based site we're working on. Chaplin requires the use of a module system like AMD/Common.js and I want to make sure my compiled javascript file will usable within CQ5's clientlibs. Is it as simple as adding require.js as a dependency in clientlibs prior to loading in my javascript modules? Someone's insight who has experience in doing this would be greatly appreciated.
I've implemented this as a solution of organize in a better way all the modules such as:
//public/js/modules/myModule.js
define('myModule',[ /* dependencies */] ,function( /* stuff here */ ))
and in the components such:
<% //components/component.jsp %>
<div>
<!-- stuff here -->
</div>
componentJS:
//components/component/clientlibs/js/component.js
require(['modules/myModule']);
and finally I've configured require (config.js) and I've stored the JSs modules in a new different design folder. Located the compiled JS after close </body> to guarantee the JS is always located at the bottom after the HTML.
<!-- page/body.jsp -->
...
<cq:includeClientLib js="specialclientlibs.footer"/>
</body>
solving with this the issue of have "ready" all the content before the JS is executed. I've had some problems to resolve with this async stuff managed for the clienlibs compilation tool, in production the problem was different, however, in development, the order in what CQ compiles the JS has produced me some lacks in terms of order of the JS. The problem really was a little bit more complex than the explanation because the number of JS was really big and the team too, but in simple terms it was the best way I've discovered so far..
The Idea
I think you can compile your Chaplin.js with one of the AMDShims to make it self contained, wraps every dependencies it needs inside a function scope, expose an entry point as global variable (which is a bad practise, but CQ do it all the time...) and then use the compiled.js inside a normal clientlib:
AMD Shims
https://github.com/jrburke/requirejs/wiki/AMD-API-Shims
Example
Here is an example of how we make the one of our libs self-contained:
https://github.com/normanzb/chuanr/blob/master/gruntfile.js
Basically, in source code level the lib "require"s the other modules just as usual. However after compiled, the generated chuanr.js file contains everything its needs, even wrapped a piece of lightweight AMD compatible implementation.
check out compiled file here: https://github.com/normanzb/chuanr/blob/master/Chuanr.js
and the source code: https://github.com/normanzb/chuanr/tree/master/src
Alternative
Alternatively rather than compile every lib you are using to be independent/self-contained, what we do in our project is simply use below amdshim instead of the real require.js. so on cq component level you can call into require() function as usual:
require(['foo/bar'], function(){});
The amd shim will not send the http request to the module immediately, instead it will wait until someone else loads the module.
and then at the bottom of the page, we collect all the dependencies, send the requirements to server side handler (scriptmananger) for dynamic merging (by internally calling into r.js):
var paths = [];
for (var path in amdShim.waiting){
paths.push(path);
}
document.write('/scriptmananger?' + paths.join(','));
The amdShim we are using: https://github.com/normanzb/amdshim/tree/exp/defer

Categories

Resources