How to lazyload library in Angular 4 module? - javascript

I have an app with multiple modules.
One of the modules is to visualize pdf. I use pdf.js which is pretty greedy and the vendor.js is somehow big because of this.
Is there a way to lazyload the library at the same time I lazy load the pdf-module ?
I've noticed this answer, but it doesn't feel as right.
Load external js script dynamically in Angular 2
I am not trying to lazyload a module but an external library.

If you want to lazy load external libraries such as jquery, jspdf you can create some service like:
lazy-loading-library.service.ts
import { Injectable, Inject } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { ReplaySubject } from 'rxjs/ReplaySubject';
import { DOCUMENT } from '#angular/platform-browser';
#Injectable()
export class LazyLoadingLibraryService {
private loadedLibraries: { [url: string]: ReplaySubject<any> } = {};
constructor(#Inject(DOCUMENT) private readonly document: any) { }
public loadJs(url: string): Observable<any> {
if (this.loadedLibraries[url]) {
return this.loadedLibraries[url].asObservable();
}
this.loadedLibraries[url] = new ReplaySubject();
const script = this.document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onload = () => {
this.loadedLibraries[url].next('');
this.loadedLibraries[url].complete();
};
this.document.body.appendChild(script);
return this.loadedLibraries[url].asObservable();
}
}
And whenever you need some external library just use this service that will load library only once:
app.component.ts
export class AppComponent {
constructor(private service: LazyLoadingLibraryService) {}
loadJQuery() {
this.service.loadJs('https://code.jquery.com/jquery-3.2.1.min.js').subscribe(() => {
console.log(`jQuery version ${jQuery.fn.jquery} has been loaded`);
});
}
loadJsPdf() {
this.service.loadJs('https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js').subscribe(() => {
console.log(`JsPdf library has been loaded`);
});
}
Plunker Example
If you're looking for lazy loading angular module then these questions might be helpful for you:
How to manually lazy load a module?
How to lazy load Angular 2 components in a TabView (PrimeNG)?

I hope you're using Angular CLI.
Install pdfjs-dist package:
npm install pdfjs-dist
Install types for it:
npm install #types/pdfjs-dist --save-dev
Add the following import statement to your lazy loaded module file:
import 'pdfjs-dist';
The last step will embed pdf.js source code in the lazy loaded bundle when you run ng build.
You should be able to access the global PDFJS variable from your code.
Hope this helps.

Related

Angular Lazy Load External JS files with Angular Universal

https://maps.googleapis.com/maps/api/js?libraries=places&key=XXX
This is inside index.html file, but i want to lazy load this script, because that module is lazy loaded and it's really not necessary for all users.
I can't use trick with directly accessing the DOM and appending script el. because I want to use Angular Universal ( SSR ).
You can access the DOM even if you are using SSR. Add this to your lazy loaded module module or one of the components of your lazy loaded module
import {DOCUMENT} from "#angular/common";
import {Renderer2} from '#angular/core';
constructor(#Inject(DOCUMENT) private document: any, private renderer: Renderer2)
{
}
constructor()
{
const scriptElt = this.renderer.createElement('script');
this.renderer.setAttribute(scriptElt, 'type', 'text/javascript');
this.renderer.setAttribute(scriptElt, 'src', 'yourJSFile.js');
this.renderer.appendChild(this.document.head, scriptElt);
}

How to use an external third party library in Stencil.js

I have a Stencil component and, as part of its business logic, I need to use an external Javascript file mylib.js. The Javascript file contains some business logic the Stencil component should use.
Here's my component:
import { Component, Element, Prop, h, Host } from '#stencil/core';
import moment from 'moment';
import mylib from 'src/js/mylib.js';
#Component({
tag: 'dashboard-widget',
styleUrl: 'dashboard-widget.css',
shadow: false
})
export class DashboardWidget {
#Element() el: HTMLElement;
#Prop() canvas: HTMLElement;
#Prop() channelName: string = "";
#Prop() channelValue: string = "";
#Prop() isBlinking: boolean = true;
componentDidLoad() {
console.log(mylib.test());
}
render() {
return (
<Host>
<div class="card-content card-content-padding">
<b>{this.channelName}</b>
<h1 class="dashboard-card-value">{this.channelValue}</h1>
<canvas class="dashboard-card-canvas"></canvas>
</div>
</Host>
);
}
}
I keep getting the error
TypeScript Cannot find module 'src/js/mylib.js'.
I tried:
import mylib from 'src/js/mylib.js';
import 'src/js/mylib.js';
import 'mylib' from 'src/js/mylib.js';
to no avail.
The mylib.js file is inside the js folder.
The online documentation doesn't mention at all how to import external libraries. I've been successful importing moment.js but only because I installed it first by doing:
npm install moment
and then importing it inside the component by doing:
import moment from 'moment';
I also tried to "import" the external JS library by referencing it inside the index.html
<script src="assets/js/mylib.js"></script>
The library is available outside the component but not inside it
Since you're mentioning Moment.js, I'll explain how to load that first. It's possible to do it the way you did by importing it inside your component's module, however that will result in a large bundle size because the npm package of moment is not targeted for browsers but for use in Node.js projects where bundle size doesn't matter. Moment.js distributes browser bundles inside the package though. So what you can do is add a copy task to your Stencil output target to copy node_modules/moment/min/moment.min.js into your build directory:
// stencil.config.ts
import { Config } from '#stencil/core';
export const config: Config = {
namespace: 'my-app',
outputTargets: [
{
type: 'www',
copy: [
{
src: '../node_modules/moment/min/moment.min.js',
dest: 'lib/moment.min.js'
}
]
}
]
};
Then, as you already tried with your lib, you can load that script in src/index.html:
<script src="/lib/moment.min.js"></script>
However, your Typescript project won't know yet that moment is available in the global scope. That's easy to solve though, you can just add a declaration file somewhere in your project, e. g. src/global.d.ts with the content
import _moment from 'moment';
declare global {
const moment: typeof _moment;
}
For your test files which run in the Node.js context, not a browser context, you can either import moment or also add moment to the global scope, by creating a file (e. g. jest-setup-file.js) with the content
global.moment = require('moment');
and then in stencil.config.ts you just add the setupFilesAfterEnv field to testing:
{
testing: {
setupFilesAfterEnv: ['<rootDir>/jest-setup-file.js']
}
}
If you don't need the script in your whole application but only when a specific component is loaded, it makes more sense to only load the script from within that component. The easiest way to do that is to create a script element and add it to the DOM:
declare const MyLib: any; // assuming that `mylib.js` adds `MyLib` to the global scope
export class MyComp {
componentWillLoad() {
const src = "assets/js/mylib.js";
if (document.querySelector(`script[src="${src}"]`)) {
return; // already exists
}
const script = document.createElement('script');
script.src = src;
document.head.appendChild(script);
}
}
Your script/library will most likely also contribute a variable to the global scope, so you'll have to let Typescript know again, which you can do using the declare keyword to declare that a variable exists in the global context (see https://www.typescriptlang.org/docs/handbook/declaration-files/by-example.html#global-variables).
As another example, here's a helper I wrote to load the google maps api:
export const importMapsApi = async () =>
new Promise<typeof google.maps>((resolve, reject) => {
if ('google' in window) {
return resolve(google.maps);
}
const script = document.createElement('script');
script.onload = () => resolve(google.maps);
script.onerror = reject;
script.src = `https://maps.googleapis.com/maps/api/js?key=${googleApiKey}&libraries=places`;
document.body.appendChild(script);
});
(The google type comes from the #types/googlemaps package)
I can then use this like
const maps = await importMapsApi();
const service = new maps.DistanceMatrixService();
To import files that aren't installed by NPM you can use relative paths prefixed with ./ or ../:
import mylib from '../../js/mylib.js';
You can import everything that is exported from that JS file and even use named imports:
mylib.js
export function someFunction() {
// some logic
}
dashboard-widget.tsx
import { someFunction } from '../../js/mylib.js`;
const result = someFunction();

Load new modules dynamically in run-time with Angular CLI & Angular 5

Currently I'm working on a project which is being hosted on a clients server. For new 'modules' there is no intention to recompile the entire application. That said, the client wants to update the router/lazy loaded modules in runtime. I've tried several things out but I can't get it to work. I was wondering if any of you knows what I could still try or what I missed.
One thing I noticed, most of the resources I tried, using angular cli, are being bundled into seperate chunks by webpack by default when building the application. Which seems logical as it makes use of the webpack code splitting. but what if the module is not known yet at compile time (but a compiled module is stored somewhere on a server)? The bundling does not work because it can't find the module to import. And Using SystemJS will load up UMD modules whenever found on the system, but are also bundled in a seperate chunk by webpack.
Some resources I already tried;
dynamic-remote-component-loader
module-loading
Loading modules from different server at runtime
How to load dynamic external components into Angular application
Implementing a plugin architecture / plugin system / pluggable framework in Angular 2, 4, 5, 6
Angular 5 - load modules (that are not known at compile time) dynamically at run-time
https://medium.com/#nikolasleblanc/building-an-angular-4-component-library-with-the-angular-cli-and-ng-packagr-53b2ade0701e
Some several other relating this topic.
Some code I already tried and implement, but not working at this time;
Extending router with normal module.ts file
this.router.config.push({
path: "external",
loadChildren: () =>
System.import("./module/external.module").then(
module => module["ExternalModule"],
() => {
throw { loadChunkError: true };
}
)
});
Normal SystemJS Import of UMD bundle
System.import("./external/bundles/external.umd.js").then(modules => {
console.log(modules);
this.compiler.compileModuleAndAllComponentsAsync(modules['External'])
.then(compiled => {
const m = compiled.ngModuleFactory.create(this.injector);
const factory = compiled.componentFactories[0];
const cmp = factory.create(this.injector, [], null, m);
});
});
Import external module, not working with webpack (afaik)
const url = 'https://gist.githubusercontent.com/dianadujing/a7bbbf191349182e1d459286dba0282f/raw/c23281f8c5fabb10ab9d144489316919e4233d11/app.module.ts';
const importer = (url:any) => Observable.fromPromise(System.import(url));
console.log('importer:', importer);
importer(url)
.subscribe((modules) => {
console.log('modules:', modules, modules['AppModule']);
this.cfr = this.compiler
.compileModuleAndAllComponentsSync(modules['AppModule']);
console.log(this.cfr,',', this.cfr.componentFactories[0]);
this.external.createComponent(this.cfr.componentFactories[0], 0);
});
Use SystemJsNgModuleLoader
this.loader.load('app/lazy/lazy.module#LazyModule')
.then((moduleFactory: NgModuleFactory<any>) => {
console.log(moduleFactory);
const entryComponent = (<any>moduleFactory.moduleType).entry;
const moduleRef = moduleFactory.create(this.injector);
const compFactory = moduleRef.componentFactoryResolver
.resolveComponentFactory(entryComponent);
});
Tried loading a module made with rollup
this.http.get(`./myplugin/${metadataFileName}`)
.map(res => res.json())
.map((metadata: PluginMetadata) => {
// create the element to load in the module and factories
const script = document.createElement('script');
script.src = `./myplugin/${factoryFileName}`;
script.onload = () => {
//rollup builds the bundle so it's attached to the window
//object when loaded in
const moduleFactory: NgModuleFactory<any> =
window[metadata.name][metadata.moduleName + factorySuffix];
const moduleRef = moduleFactory.create(this.injector);
//use the entry point token to grab the component type that
//we should be rendering
const compType = moduleRef.injector.get(pluginEntryPointToken);
const compFactory = moduleRef.componentFactoryResolver
.resolveComponentFactory(compType);
// Works perfectly in debug, but when building for production it
// returns an error 'cannot find name Component of undefined'
// Not getting it to work with the router module.
}
document.head.appendChild(script);
}).subscribe();
Example with SystemJsNgModuleLoader only works when the Module is already provided as 'lazy' route in the RouterModule of the app (which turns it into a chunk when built with webpack)
I found a lot of discussion about this topic on StackOverflow here and there and provided solutions seem really good of loading modules/components dynamically if known up front. but none is fitting for our use case of the project. Please let me know what I can still try or dive into.
Thanks!
EDIT: I've found; https://github.com/kirjs/angular-dynamic-module-loading and will give this a try.
UPDATE: I've created a repository with an example of loading modules dynamically using SystemJS (and using Angular 6); https://github.com/lmeijdam/angular-umd-dynamic-example
I was facing the same problem. As far as I understand it until now:
Webpack puts all resources in a bundle and replaces all System.import with __webpack_require__. Therefore, if you want to load a module dynamically at runtime by using SystemJsNgModuleLoader, the loader will search for the module in the bundle. If the module does not exist in the bundle, you will get an error. Webpack is not going to ask the server for that module. This is a problem for us, since we want to load a module that we do not know at build/compile time.
What we need is loader that will load a module for us at runtime (lazy and dynamic). In my example, I am using SystemJS and Angular 6 / CLI.
Install SystemJS: npm install systemjs –save
Add it to angular.json: "scripts": [ "node_modules/systemjs/dist/system.src.js"]
app.component.ts
import { Compiler, Component, Injector, ViewChild, ViewContainerRef } from '#angular/core';
import * as AngularCommon from '#angular/common';
import * as AngularCore from '#angular/core';
declare var SystemJS;
#Component({
selector: 'app-root',
template: '<button (click)="load()">Load</button><ng-container #vc></ng-container>'
})
export class AppComponent {
#ViewChild('vc', {read: ViewContainerRef}) vc;
constructor(private compiler: Compiler,
private injector: Injector) {
}
load() {
// register the modules that we already loaded so that no HTTP request is made
// in my case, the modules are already available in my bundle (bundled by webpack)
SystemJS.set('#angular/core', SystemJS.newModule(AngularCore));
SystemJS.set('#angular/common', SystemJS.newModule(AngularCommon));
// now, import the new module
SystemJS.import('my-dynamic.component.js').then((module) => {
this.compiler.compileModuleAndAllComponentsAsync(module.default)
.then((compiled) => {
let moduleRef = compiled.ngModuleFactory.create(this.injector);
let factory = compiled.componentFactories[0];
if (factory) {
let component = this.vc.createComponent(factory);
let instance = component.instance;
}
});
});
}
}
my-dynamic.component.ts
import { NgModule, Component } from '#angular/core';
import { CommonModule } from '#angular/common';
import { Other } from './other';
#Component({
selector: 'my-dynamic-component',
template: '<h1>Dynamic component</h1><button (click)="LoadMore()">LoadMore</button>'
})
export class MyDynamicComponent {
LoadMore() {
let other = new Other();
other.hello();
}
}
#NgModule({
declarations: [MyDynamicComponent],
imports: [CommonModule],
})
export default class MyDynamicModule {}
other.component.ts
export class Other {
hello() {
console.log("hello");
}
}
As you can see, we can tell SystemJS what modules already exist in our bundle. So we do not need to load them again (SystemJS.set). All other modules that we import in our my-dynamic-component (in this example other) will be requested from the server at runtime.
I've used the https://github.com/kirjs/angular-dynamic-module-loading solution with Angular 6's library support to create an application I shared on Github. Due to company policy it needed to be taken offline. As soon as discussions are over regarding the example project source I will share it on Github!
UPDATE: repo can be found ; https://github.com/lmeijdam/angular-umd-dynamic-example
I have tested in Angular 6, below solution works for dynamically loading a module from an external package or an internal module.
1. If you want to dynamically load a module from a library project or a package:
I have a library project "admin" (or you can use a package) and an application project "app".
In my "admin" library project, I have AdminModule and AdminRoutingModule.
In my "app" project:
a. Make change in tsconfig.app.json:
"compilerOptions": {
"module": "esNext",
},
b. In app-routing.module.ts:
const routes: Routes = [
{
path: 'admin',
loadChildren: async () => {
const a = await import('admin')
return a['AdminModule'];
}
},
{
path: '',
redirectTo: '',
pathMatch: 'full'
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
2. if you want to load a module from the same project.
There are 4 different options:
a. In app-routing.module.ts:
const routes: Routes = [
{
path: 'example',
/* Options 1: Use component */
// component: ExampleComponent, // Load router from component
/* Options 2: Use Angular default lazy load syntax */
loadChildren: './example/example.module#ExampleModule', // lazy load router from module
/* Options 3: Use Module */
// loadChildren: () => ExampleModule, // load router from module
/* Options 4: Use esNext, you need to change tsconfig.app.json */
/*
loadChildren: async () => {
const a = await import('./example/example.module')
return a['ExampleModule'];
}
*/
},
{
path: '',
redirectTo: '',
pathMatch: 'full'
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
``
Do it with angular 6 library and rollup do the trick. I've just experiment with it and i can share standalone angular AOT module with the main app without rebuild last.
In angular library set angularCompilerOptions.skipTemplateCodegen to false and after build library you will get module factory.
After that build an umd module with rollup like this:
rollup dist/plugin/esm2015/lib/plugin.module.ngfactory.js --file src/assets/plugin.module.umd.js --format umd --name plugin
Load text source umd bundle in main app and eval it with module context
Now you can access to ModuleFactory from exports object
Here https://github.com/iwnow/angular-plugin-example you can find how develop plugin with standalone building and AOT
I believe this is possible using SystemJS to load a UMD bundle if you build and run your main application using webpack. I used a solution that uses ng-packagr to build a UMD bundle of the dynamic plugin/addon module. This github demonstrates the procedure described:
https://github.com/nmarra/dynamic-module-loading
Yes, you can lazy load modules using by referring them as modules in the router. Here is an example https://github.com/start-angular/SB-Admin-BS4-Angular-6
First couple all the components that you are using into a single module
Now refer that module in the router and angular will lazy load your module into the view.

How to include external JavaScript libraries in Angular 2?

I am trying to include an external JS library in my Angular 2 app and trying to make all the methods in that JS file as a service in Angular 2 app.
For eg: lets say my JS file contains.
var hello = {
helloworld : function(){
console.log('helloworld');
},
gmorning : function(){
console.log('good morning');
}
}
So I am trying to use this JS file and reuse all the methods in this object and add it to a service, so that my service has public methods, which in turn calls this JS methods. I am trying to reuse the code, without reimplementing all the methods in my typescript based Angular 2 app. I am dependent on an external library, which I cant modify.
Please help, thank you in advance.
With ES6, you could export your variable:
export var hello = {
(...)
};
and import it like this into another module:
import {hello} from './hello-module';
assuming that the first module is located into the hello-module.js file and in the same folder than the second one. It's not necessary to have them in the same folder (you can do something like that: import {hello} from '../folder/hello-module';). What is important is that the folder is correctly handled by SystemJS (for example with the configuration in the packages block).
When using external libs which are loaded into the browser externally (e.g. by the index.html) you just need to say your services/component that it is defined via "declare" and then just use it. For example I recently used socket.io in my angular2 component:
import { Component, Input, Observable, AfterContentInit } from angular2/angular2';
import { Http } from 'angular2/http';
//needed to use socket.io! io is globally known by the browser!
declare var io:any;
#Component({
selector: 'my-weather-cmp',
template: `...`
})
export class WeatherComp implements AfterContentInit{
//the socket.io connection
public weather:any;
//the temperature stream as Observable
public temperature:Observable<number>;
//#Input() isn't set yet
constructor(public http: Http) {
const BASE_URL = 'ws://'+location.hostname+':'+location.port;
this.weather = io(BASE_URL+'/weather');
//log any messages from the message event of socket.io
this.weather.on('message', (data:any) =>{
console.log(data);
});
}
//#Input() is set now!
ngAfterContentInit():void {
//add Observable
this.temperature = Observable.fromEvent(this.weather, this.city);
}
}

How to import Parse JS sdk into ionic 2 beta

am trying to import JS sdk into ionic 2 app, but i keep getting parse is undefined
In ionic 1.x ,parse js sdk is loaded via
<script ..parse.js </script>
and exposed as a global var, how do import in ionic 2 ,am using the npm module ,and tried
import * as parse from 'parse'
Do npm install parse --save in your project directory
Then import parse using
import { Parse } from 'parse';
It is better to create an parse provider.
You can use this starter template as a guide. It is a simple GameScores application in ionic to get you started.
https://github.com/Reinsys/Ionic-Parse
It shows how to create and read data from parse server. I also includes paging with ion-infinite-scroll scrolling.
After searching for a solution I came up with my own.
After installing the package and the typings, I opened the index.js of the node-module ionic-gulp-scripts-copy and added 'node_modules/parse/dist/parse.min.js' to the defaultSrc array.
Then, in my index.html, I included the script above the cordova.js.
Now I just need to declare var Parse: any; in every Component I want to use the SDK in.
For example, in my app.ts:
import {Component} from '#angular/core';
import {Platform, ionicBootstrap} from 'ionic-angular';
import {StatusBar} from 'ionic-native';
import {TabsPage} from './pages/tabs/tabs';
import{LoginPage} from './pages/login/login';
declare var Parse: any;
#Component({
template: '<ion-nav [root]="rootPage"></ion-nav>',
})
export class MyApp {
private rootPage: any;
private parse;
constructor(private platform: Platform) {
//this.rootPage = TabsPage;
this.rootPage = LoginPage;
platform.ready().then(() => {
console.log("Platform ready!");
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
StatusBar.styleDefault();
Parse.initialize('myStartUp', 'someKey');
Parse.serverURL = 'http://localhost:1337/parse';
});
}
}
ionicBootstrap(MyApp);
I do not think this is the way it should be used, but in the end I can use the SDK pretty easy and without much lines of implementation code.

Categories

Resources