Generate appropriate Angular Element dynamically without bloating the build size? - javascript

Summary:
When createCustomElement() is called multiple times inside a switch case, all of the components will be included in the build, instead of just the one that will actually be used. This increases the build size with duplicate code.
Details
I have an Angular 11 app with a multi-site architecture. There is a project in the angular.json for each site, so they can be built independently and generate their own dist bundles based on the appropriate environment.ts file that contains a "siteCode".
For one of the big components in my site -- let's call it myWidget -- I also export it as a generic web component (a.k.a "Angular Element", a.k.a. "custom element") for other sites to consume. So I have myWidget in a sub-project of the main app, and it also has its own projects listed in angular.json. Meaning I can run a build that should contain just myWidget for a given site (along with the core Angular framework, obviously).
app.module.ts of myWidget sub-project (simplified):
import { MyWidgetSite1Component } from './my-widget/site-widgets/my-widget-site1.component';
import { MyWidgetSite2Component } from './my-widget/site-widgets/my-widget-site2.component';
import { MyWidgetSite3Component } from './my-widget/site-widgets/my-widget-site3.component';
#NgModule({
declarations: [AppComponent],
imports: [MyWidgetModule]
})
export class AppModule {
constructor(private injector: Injector) {
//Create generic web component version of myWidget. Use correct child version per site.
switch (environment.siteCode) {
case "site1": {
const myWidgetCustomElement = createCustomElement(MyWidgetSite1Component , { injector: this.injector });
customElements.define('site1-myWidget', myWidgetCustomElement);
break;
}
case "site2": {
const myWidgetCustomElement = createCustomElement(MyWidgetSite2Component , { injector: this.injector });
customElements.define('site2-myWidget', myWidgetCustomElement);
break;
}
case "site3": {
const myWidgetCustomElement = createCustomElement(MyWidgetSite3Component , { injector: this.injector });
customElements.define('site3-myWidget', myWidgetCustomElement);
break;
}
}
}
}
Problem: it includes all three of those components in the build, instead of just the one that will be used for that site (verified with webpack bundle analyzer).
Futher background
The three site-specific myWidget components here all inherit from a common base component where all the real logic is, so they are nearly-identical. I'm doing this so I can load the appropriate CSS files for that site and bundle them inside the exported MyWidget web component as component-specific CSS. It uses shadowDom encapsulation and this way the web component is completely sealed off from the parent page that it's inserted into. So the components in question look like this:
my-widget-site1.component.ts
#Component({
selector: 'my-widget-site1',
templateUrl: '../my-widget/my-widget.component.html', //Shares base myWidget template
//First file does nothing but import appropriate site's stylesheets from main project. It would
//have been better to directly include them here, but that resulted in odd build errors.
styleUrls: [
'./my-widget-site1.component.scss',
'../my-widget/my-widget.component.scss'],
encapsulation: ViewEncapsulation.ShadowDom
})
export class MyWidgetSite1Component extends MyWidgetComponent implements OnInit {
//Do not add any code here
}
my-widget-site1.component.scss
#import '../../../../../../src/app/sites/site1/theme.scss';
#import '../../../../../../src/styles.scss';
#import '../../../../../../src/app/sites/site1/styles.scss';
Conclusion
I can think of a few general ideas to solve this:
1) Some trick to load the desired component dynamically instead of in a switch case?
I haven't been able to find anything. It seems as long as I have to import the component, it will be included in the build.
2) Avoid having multiple versions of the component per site entirely?
I would love to do this, but I don't know how to get around the CSS problem. The appropriate CSS files for a given site need to be bundled into this component at build time so they are encapsulated in the shadow-root of the web component and not built as a separate CSS file that gets imported into the global scope of the consuming page. That means I can't just list them in the "styles" section of the project build in angular.json
I tried to do a dynamic #import statement on the scss but that doesn't seem possible.
Can you script something into the build process somehow to choose the right scss files at build time? I would have no idea where to start with something like that.

I figured out an interesting solution to this.
I can get rid of the need for multiple component files and effectively pull off a dynamic #import by using a 'shortcut' to point at the necessary scss files instead of the full path:
#import "theme";
#import "styles";
#import "site-styles";
You can configure the folders it will find the specified files in via angular.json:
"stylePreprocessorOptions": {
"includePaths": [
"src/app/sites/site1/", //theme.scss and site-styles.scss are here
"src/" //styles.scss is here
]
}
So now I can use one component that always has the same imports, but at build time it will actually use the right file for the site being built.
Info about the shortcut syntax: https://www.digitalocean.com/community/tutorials/angular-shortcut-to-importing-styles-files-in-components

Related

How to use JavaScript files in angular

I am trying to call the javascript function into the angular here is the plugin I am using "npm I global payments-3ds" of which I copied javascript files from node_modules and tried to call in my component
Below is the example :
import {
Component,
OnInit
} from '#angular/core';
import {
handleInitiateAuthentication
} from './globalpayments-3ds/types/index';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
name = 'Angular';
ngOnInit(): void {
const status: any = "CHALLENGE_REQUIRED"
const resp = {
challenge: {
encodedChallengeRequest: "abcd",
requestUrl: "url,
},
challengeMandated: "MANDATED",
dsTransactionId: "44444",
id: "444444",
status: status,
};
const windowSize: any = "WINDOWED_600X400";
const displayMode: any = "lightbox";
const challengeWindow = {
windowSize: windowSize,
displayMode: displayMode,
};
handleInitiateAuthentication(resp, challengeWindow)
}
}
I am trying to call the handleInitiateAuthentication() which is giving me the below error
Here is the file structure
from index.d.ts i am calling the handleInitiateAuthentication() function
Here is Stackblitz code for the same
https://stackblitz.com/edit/angular-vodezz?file=src%2Fapp%2Fapp.component.ts
Please help I never used the js function in angular I tried to add in assets not worked
I have tried to create an angular library and add the js files in it and update the package, by converting the file to .tgz but nothing working it showing always the same error,
Why am I doing is I have to update one of the files from node_modules, basically I wanna change files from node modules which is why i copied those files locally
this is also giving error
You have to import directly js file.
// #ts-ignore
import { handleInitiateAuthentication } from './globalpayments-3ds/globalpayments-3ds.esm.js';
For error about module, it's because you have to define type of your module in TypeScript. You can directly use // #ts-ignore.
See this stackblitz : https://stackblitz.com/edit/angular-xz4kmp?file=src%2Fapp%2Fapp.component.ts
You don't need to import a library like that. First of all install the library to your project:
npm i globalpayments-3ds --save
then in your ts file:
import { handleInitiateAuthentication } from 'globalpayments-3ds';
see this stackblitz
The recommended way to make your own modified versions from open source libraries is to fork them and build your own versions.
Also note that you must take into account the license of that NPM package which in the case of https://github.com/globalpayments/globalpayments-js is GPL-v2, so if you will use it for commercial purposes you must follow the agreement. Check this branch: GNU General Public License (v2): can a company use the licensed software for free?.
Taking a look to your Stackblitz code, you may notice that there are several JS versions of the same module in src/app/global-payments-3ds/ folder:
globalpayments-3ds.js (CommonJS, used in Node environments).
globalpayments-3ds.min.js (CommonJS minified).
globalpayments-3ds.js.map (CommonJS minified map file to reference during debugging).
globalpayments-3ds.esm.js (ESM, ECMA Standard Module).
...
To use an external JS Module in an Angular App, as it is JavaScript and not TypeScript, you must tell TypeScript Compiler that you want to allow JS modules by enabling allowJS: true in tsconfig.ts file at the root of the project.
After that you should be be able to import the ESM version (globalpayments-3ds.esm.js) in your Angular App, or if you want to use the CommonJS version, you can also enable esModuleInterop: true in tsconfig.ts to allow importing CommonJS/AMD/UMD JS modules in your project, like globalpayments-3ds.js.

ClassName/ClassName.js Module Resolution with Webpack & Node.js

Often times I see the following directory structure and import pattern in Javascript projects:
ClassName/index.js pattern
RepoRoot
|-src
|-index.js
|-ClassName
|-index.js
|-SupportingClass.js
src/ClassName/index.js
import { SupportingClass } from './SupportingClass';
export class ClassName {
// Implementation
}
src/index.js
import { ClassName } from './ClassName';
This is all fine and dandy. It allows for a much cleaner import of the ClassName class. However I'm not a fan of the name of the class file index.js not having the same name as the class's name. It:
Makes it harder to locate the file in a file name search (Command+P in VS Code)
You end up with just a very unhelpful index.js in the file tab in the IDE (yes I know some IDEs are smart enough to add a bit more context when you have more than one file of the same name open. That helps, but isn't a real solution imo)
Other files that aren't the indexes get much more descriptive names: SupportingClass.js, someUtils.js, etc.
ClassName/ClassName.js pattern
RepoRoot
|-src
|-index.js
|-ClassName
|-ClassName.js
|-SupportingClass.js
src/ClassName/ClassName.js
import { SupportingClass } from './SupportingClass';
export class ClassName {
// Implementation
}
src/index.js
import { ClassName } from './ClassName/ClassName';
This solves all of the problems I laid out, but makes the import of ClassName a bit duplicative. Probably not a big deal for most people especially with your IDE being able to auto import things for you nowadays.
However...
Just how webpack & node.js understand out of the box how to interpret the import path:
./ClassName as ./ClassName/index.js
Is there a setting or plugin that allows for it to interpret:
./ClassName as ./ClassName/ClassName.js?
I've been wondering for years if such a thing existed but could never really find any literature on it. Curious if anyone here knows of anything.
You are dealing with named imports and default imports, more details on this discussion can be found here:
How to import both default and named from an ES6 module
From your situation (I haven't tried with subfolders, but it should work), you may want to organize your files as such:
RepoRoot
|-src
|-index.js
|-ClassName
|-ClassName.js (named module)
|-SupportingClass.js (named module)
|-index.js (default modules)
And then you can easily import your stuff in src/index.js such as:
import ClassName, SupportingClass, { otherValues } from './ClassName'

VueJs 3 - Use bundled sfc combined with Client Side Rendering

Greetings
Hello fellow Vuers!
So I've got the following situation:
I use ASP.Net Core 3.1 as my server and I would like to use the Vue SFC setup including Typescript support and bind the resulting components into my .cshtml.
Example Usage
Example.vue
<template>
<label :for="name">{{ content }}</label>
<input :id="name" :placeholder="content"/>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
someCode
}),
</script>
<style scoped>
/*some styling*/
</style>
Index.cshtml.cs
public class IndexModel: PageModel{
public string Name { get; set; }
public string Content { get; set; }
}
Index.cshtml
#page
#model Namespace.To.IndexModel
<example :name="#Model.Name" :content="#Model.Content" />
The Question
Is there a way to bundle the Single File Components and then use the Components as needed inside of a .(cs)html?
Preferably I'd like to have each component inside of it's own .js file to load them on demand, but it's not a must have.
Thanks in advance
It is possible. But to clarify, it seems like you want to use the components individually. That means that what you're calling a SFC/component, will need to be treated as its own Vue app.
Assuming that's the case, instead of making the components bundled separately you'll need to create a vue app for each one, and individually export them.
You will need to decide how/when to mount them. I've relied on a more manual way of mounting, which requires a line of js to link the DOM element with the widget and pass the attributes. Alternatively you can rely on the DOM tag only. Admittedly, the js way is a bit more verbose, but less prone to edge cases.
Here is the example for the js way
components/example/index.js:
import Example from './Example.vue';
export const mountExample = (el, props) =>
Vue.createApp(el, props);
Then will wrap the component in a function that allows you to pass the DOM element to use and the props.
You would need
<script src="vue.js"/><!-- if it's not bundled in there -->
<script src="example.js"/>
<div id="example" />
<script>
mountExample('#example', {name:"#Model.Name", content="#Model.Content});
</script>
The other way (without the js instantiation) would be to wrap it in a function (IIFE) that looks for <example> tags, parses the content and then mounts the app with the provided parameters. It's quite a bit more work than the other example, but shouldn't be terribly complex.
So for the Example example, I'd organize it something like this: example
/components/example/
|-- Example.vue
|-- index.js
and then use webpack chaining via vue.config.js to do multiple of these
module.exports = {
// tweak internal webpack configuration.
// see https://github.com/vuejs/vue-cli/blob/dev/docs/webpack.md
chainWebpack: config => {
// remove the standard entry point
config.entryPoints.delete('app')
// then add your own
config.entry('example')
.add('./src/components/example/index.js')
.end()
.entry('menu')
.add('./src/components/menu/index.js')
.end()
}
}
A caveat; I've used rollup to generate these and I haven't tested this, but webpack should work too
resources for the webpack config:
https://cli.vuejs.org/guide/webpack.html#simple-configuration
https://github.com/neutrinojs/webpack-chain

How to access external javascript file from angular 2 component

I am very new to angular and front end web development, so maybe i am missing something
basic but i did not succeed to search a solution for that issue.
according to that answer: Call pure javascript function from Angular 2 component
and following that example
I am trying to import external .js file to my angular component:
import '../../../src/Plugin/codemirror/mode/custom/custom.js'
#Component({
selector: 'txt-zone',
templateUrl: 'app/txtzone/Txtzone.component.html',
styleUrls: ['app/txtzone/TxtZone.css'],
})
the path is the correct relative path, i know that because if it loads diractly from the url text box via the browser [http://localhost:50371/src/Plugin/codemirror/mode/custom/custom.js]
i can see the file content...
this is the exception that the chrome debugger is throwing:
zone.js:2263 GET
http://localhost:50371/src/Plugin/codemirror/lib/codemirror 404 (Not
Found)
as you can see the path was changed (don`t understand why?)
1. how can i solve this issue?
2. why the path of the .js file is not the referenced path?
3. maybe there is a better way to load external .js file into my component?
it looks quite trivial question but after hours of searching i could not find any answer.
A simple way to include custom javascript functions in your Angular 4 project is to include the item in your assets folder, and then use require to import it into your component typescript.
src/assets/example.js
export function test() {
console.log('test');
}
src/app/app.component.ts
(before #Component(...))
declare var require: any;
const example = require('../assets/example');
(inside export class AppComponent implements OnInit { ...)
ngOnInit() {
example.test();
}

Referencing in a simple way using AngularJS and TypeScript

I'm using VS2015 with Gulp and I'm trying to build AngularJS with TypeScript.
In my index.html, I have a script tag to my "app.js" (the output and bundle of the TS build).
However if I want to reference my controller, and any other services - how can I avoid having to put the relevant script tags in each and every HTML file - is there a way I can just reference the app.js file and be done with it? What's the recommended approach?
Cheers,
if you want to refrence only one file in html via script tag and other files just reference in other js files then you can use requirejs. It is a nice tool to load scripts. in production it is a good approach to concat and minify all your scripts to reduce number of requests.
I managed to resolve it using experimental typescript decorators, requirejs and a little of imagination.
So, in resume I wrote two decorators one called AppStartup and other called DependsOn. So at angular bootstrap I can get and register all dependencies.
I ended up with something like it:
TodoListController.ts
import {DependsOn, AppStartup, ngControllerBase} from "../infra/core";
import {taskManagerDirective} from "../directives/TaskManagerDirective";
#AppStartup({
Name: "TodoSample"
}).Controller({
DependsOn: [taskManagerDirective]
})
export class TodoListController extends ngControllerBase {
public ByControllerAs: string;
constructor() {
super(arguments);
let $httpPromise = this.$get<ng.IHttpService>("$http");
$httpPromise.then(function ($http) {
$http.get('http://www.google.com').success(function (body) {
console.info("google.com downloaded, source code: ", body);
});
});
this.ByControllerAs = "This was included by controllerAs 'this'";
}
}
rowListItemDirective.ts
import {DependsOn, ngDirectiveBase} from "../infra/core";
import {rowListItemDirective} from "./RowListItemDirective";
#DependsOn([rowListItemDirective])
export class taskManagerDirective extends ngDirectiveBase{
public template: string = `
Parent Directive
<table>
<tbody>
<tr row-list-item-directive></tr>
</tbody>
</table>
`;
}
You can see what I did below at my github repository:
https://github.com/klaygomes/angular-typescript-jasmine-seed

Categories

Resources