How to use Angular2 and Typescript in Jsfiddle - import

Dummy question ...
I try to code an angular2 (2.0.0-beta.6) app in Typescript in jsfiddle.
I know that there is other solution online but ...
In fact, my example is very small and the problem is on import module :
import {bootstrap} from 'angular2/platform/browser'
import {Component} from 'angular2/core';
I got the following error :
Uncaught ReferenceError: System is not defined
Uncaught ReferenceError: require is not defined
I try to add some dependencies (require, system ...) but it doesn't work.
And there is no more Self-Executing bundle for recent version (beta-6) of Angular2 (angular2.sfx.dev.js).
Some tests :
https://jsfiddle.net/asicfr/q8bwosfn/1/
https://jsfiddle.net/asicfr/q8bwosfn/3/
https://jsfiddle.net/asicfr/q8bwosfn/4/
https://jsfiddle.net/asicfr/q8bwosfn/5/
https://jsfiddle.net/asicfr/q8bwosfn/6/

In Plunker you can just use the menu
New > Angularjs > 2.0.x (TS)
to get a minimal working Angular2 application
Router
If you want to use the router add in config.js
'#angular/router': {
main: 'router.umd.js',
defaultExtension: 'js'
},
<base href="."> as first child in the <head> of index.html might be necessary as well.
To switch to HashLocationStrategy change main.ts from
import {bootstrap} from '#angular/platform-browser-dynamic';
import {App} from './app';
bootstrap(App, [])
.catch(err => console.error(err));
to
import {bootstrap} from '#angular/platform-browser-dynamic';
import {App} from './app';
import {provide} from '#angular/core'
import {ROUTER_PROVIDERS} from '#angular/router';
import {LocationStrategy, HashLocationStrategy} from '#angular/common';
bootstrap(App, [ROUTER_PROVIDERS, provide(LocationStrategy, {useClass: HasLocationStrategy}])
.catch(err => console.error(err));

If you are not tied to JS Fiddle, consider Plunker instead. The Angular devs keep a bare workspace up to date with new Angular releases at this link.
It is more current than even Plunker's own Angular 2 setup (which you can access from the Plunker menu: New > AngularJS > 2.0.x (TS)
The downside: that setup is in TypeScript, so if you wish to develop with vanilla Javascript (ES5 or ES6), your best bet is to use the Plunker menu option instead.

You need also to include SystemJS JS file. I saw that you missed it. All these includes are necessary:
<script src="https://code.angularjs.org/2.0.0-beta.3/angular2-polyfills.js"></script>
<script src="https://code.angularjs.org/tools/system.js"></script>
<script src="https://code.angularjs.org/tools/typescript.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.3/Rx.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.3/angular2.dev.js"></script>
You also need then to configure SystemJS with the following code and then import your main module containing the bootstrap function:
System.config({
transpiler: 'typescript',
typescriptOptions: { emitDecoratorMetadata: true },
packages: {
'app': {
defaultExtension: 'ts'
}
}
});
System.import('app/main')
.then(null, console.error.bind(console));

Related

SvelteKit console error "window is not defined" when i import library

I would like to import apexChart library which using "window" property, and i get error in console.
[vite] Error when evaluating SSR module /src/routes/prehled.svelte:
ReferenceError: window is not defined
I tried use a apexCharts after mount, but the error did not disappear.
<script>
import ApexCharts from 'apexcharts'
import { onMount } from 'svelte'
const myOptions = {...myOptions}
onMount(() => {
const chart = new ApexCharts(document.querySelector('[data-chart="profit"]'), myOptions)
chart.render()
})
</script>
I tried import a apexCharts when i am sure that browser exist.
import { browser } from '$app/env'
if (browser) {
import ApexCharts from 'apexcharts'
}
But i got error "'import' and 'export' may only appear at the top level"
I tried disable ssr in svelte.config.js
import adapter from '#sveltejs/adapter-static';
const config = {
kit: {
adapter: adapter(),
prerender: {
enabled: false
},
ssr: false,
}
I tried to create a component in which I import apexChart library and I created a condition that uses this component only if a browser exists
{ #if browser }
<ProfitChart />
{ /if }
Nothing helped.
Does anyone know how to help me please?
The easiest way is to simply include apexcharts like a standalone library in your webpage like this:
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
And then simply use it in the onMount:
onMount(() => {
const chart = new ApexCharts(container, options)
chart.render()
})
You can add this line either in your app.html or include it where it's required with a <svelte:head> block.
An alternative way would be to dynamically import during onMount:
onMount(async () => {
const ApexCharts = (await import('apexcharts')).default
const chart = new ApexCharts(container, options)
chart.render()
})
As an extra: use bind:this instead of document.querySelector to get DOM elements, that would be the more 'svelte' way.
I have found the last option with the Vite plugin to work best with less code in the end but will lose intellisense in vscode and see import highlighted as error (temp workaround at end): https://kit.svelte.dev/faq#how-do-i-use-x-with-sveltekit-how-do-i-use-a-client-side-only-library-that-depends-on-document-or-window
Install vite plugin: npm i -D vite-plugin-iso-import
Add plugin to svelte.config.js:
kit: {
vite: {
plugins: [
isoImport(),
],
Add plugin to TypeScript config (if you use TS):
"compilerOptions": {
"plugins": [{ "name": "vite-plugin-iso-import" }],
Use as normal but note the "?client" on the import:
<script context="module">
import { chart } from 'svelte-apexcharts?client';
import { onMount } from 'svelte'
let myOptions = {...myOptions}
onMount(() => {
myOptions = {...updated options/data}
});
</script>
<div use:chart={myOptions} />
Debugging note:
To have import not highlighting as an error temporarily, just:
npm run dev, your project will compile fine, then test in browser to execute at least once.
remove ?client now, save and continue debugging as usual.
For all of you trying to import dynamically into a js or ts file, try the following:
Import your package during on mount in any svelte component.
onMount(async () => {
const Example = await import('#creator/examplePackage');
usePackageInJSOrTS(Example.default);
});
Use the imported package in your js/ts function. You need to pass the default value of the constructor.
export function usePackageInJsOrTs(NeededPackage) {
let neededPacakge = new NeededPackage();
}

Ionic 5 / React: Use ion-icon to embed custom SVG

I have a React app in Ionic 5 and I want to add some custom SVGs to it.
This SO question is about Angular, but my question is about React.
My app folder structure looks like this:
src
assets
listen.svg
SvgListen.tsx
Here is SvgListen.tsx:
import React from 'react';
import { ReactComponent as ListenSvg } from './listen.svg';
import { IonIcon } from '#ionic/react';
const SvgListen = () => (
<>
<ListenSvg />
<IonIcon src="./listen.svg" font-size="48px" />
</>
);
export default SvgListen;
When testing the app in Chrome, I get this HTML:
<ion-icon src="./listen.svg" font-size="48px" role="img" class="ios hydrated"></ion-icon>
The <ListenSvg /> that I imported is displayed correctly; however, the ion-icon is not displayed. There is no error message, either.
I checked this blog post, but no luck with the approach outlined there, either.
How can I show a custom SVG using <IonIcon> in Ionic 5?
According do the Create React App docs you can import images to get their final path in the output bundle:
import React from 'react';
import { IonIcon } from '#ionic/react';
import listenSvg from './listen.svg';
const SvgListen = () => (
<IonIcon src={listenSvg} font-size="48px" />
);
export default SvgListen;

Getting error while using Decorators in js

I'm trying to write a simple web component using LitElement.
When I try to use:
- #customElement('my-element')
- #property()
I'm getting error.
Support for the experimental syntax 'decorators-legacy' isn't
currently enabled.
Is this something related to babel?
import { LitElement, html } from 'lit-element';
#customElement('my-element')
class MyElement extends LitElement {
render(){
return html`
<!-- template content -->
<p>A paragraph</p>
`;
}
}
JS decorators are still a proposal but they can be enabled in Babel by using #babel/plugin-proposal-decorators. Class fields also have to be enabled in order to use the #property decorator.
Install the plugins:
$ npm i -d #babel/plugin-proposal-decorators #babel/plugin-proposal-class-properties
and add them to your .babelrc:
{
"plugins": [
["#babel/plugin-proposal-decorators", {
"legacy": true
}],
"#babel/plugin-proposal-class-properties"
]
}
Decorators are a proposal for JS but are supported in Babel (as already covered by Umbo's answer, which you should accept) and natively supported by TypeScript (which Lit targets).
To use these in TS you have to add a setting to tsconfig.json:
{
"compilerOptions": {
"experimentalDecorators": true
And then import the decorators:
import {html, css, LitElement} from 'lit';
import {customElement, property} from 'lit/decorators.js';
#customElement('my-element')
class MyElement
extends LitElement {
render(){
return html`<p>A paragraph</p>`;
}
}
You should accept the Babel answer to this question, but it should be clear that this works in Typescript too.

How to Integrate MathJax with Ionic2

I'm getting template parsing errors while integrating MathJax into Ionic2 please help me with this,
package.json
"dependencies": {
.....
"mathjax": "^2.7.0"
},
home.ts
import mj from "mathjax";
home.html
<ion-card-title> Name </ion-card-title>
<span> When $a \ne 0$, there are two solutions to \(ax^2 + bx + c = 0\) and they are
$$x = {-b \pm \sqrtb^2-4ac \over 2a.}$$</span>
<button (click)= render()> Render Katex</button>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: 'inlineMath: [['$','$'], ['\\(','\\)']]}
});
</script>
<script type="text/javascript" async src="../../../node_modules/mathjax/MathJax.js?config=TeX-MML-AM_CHTML"></script>
https://www.npmjs.com/package/#types/mathjax
You need to install typescript declarations.
Try
npm install #types/mathjax --save
check out this question
I have been googling "Integrating MathJax in ionic 3 offline" for last 2 days. All I found that is I have to use a directive to achieve that. But this approach is not fast for such an app which has lots of mathematical equation. So I came up with another solution:
download MathJax offline file from here, extract and rename that with MathJax and place the whole folder in www/assets folder of your ionic app.
add the code given below in the head section of index.html file
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
imageFont: null,
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
tex2jax: {inlineMath: [["$","$"],["\\(","\\)"]]}
});
</script>
<script type="text/javascript" async
src="assets/MathJax/MathJax.js">
</script>
now for every page where you want to load mathematical equation, just paste the code below.
ionViewDidEnter() {
eval('MathJax.Hub.Queue(["Typeset", MathJax.Hub])');
}
By doing these three steps you will have integrated MathJax successfully.
But the problem is the size of MathJax folder is so big. You can reduce the size up to 3mb by just having the following directories and files
MathJax.js
extensions
fonts
HTML-CSS
TeX
eof
otf
svg
jax
element
input
TeX
output
HTML-CSS
autoload
config.js
fonts
TeX
imageFonts.js
jax.js
In your index.html file, add following script...
`
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
showProcessingMessages: false,
tex2jax: { inlineMath: [['$','$'],['\\(','\\)']] }
});
</script>
<script type="text/javascript" async src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-MML-AM_HTMLorMML">
</script>
Then make a directive for mathjax as follows
import {Directive, ElementRef, Input} from '#angular/core';
declare var MathJax: {
Hub: {
Queue: (param: Object[]) => void
}}
#Directive({selector: '[MathJax]'})
export class MathJaxDirective {
#Input('MathJax') MathJaxInput: string = "";
constructor(private el: ElementRef) {
}
ngOnChanges() {
this.el.nativeElement.innerHTML = this.MathJaxInput;
MathJax.Hub.Queue(["Typeset", MathJax.Hub, this.el.nativeElement]);
}
}
Then in app.module.ts
import {MathJaxDirective} from "... to use it in you entire app
For a condition if you have multiple modules then make a commonModule something like
import { NgModule } from "#angular/core";
import { MathJaxDirective } from "./directives/MathJax.directive";
#NgModule({
declarations: [MathJaxDirective],
exports: [MathJaxDirective]
})
export class CommonModule { }
and import this module in the required module
Now you are good to go
just in your .html
<div [Mathjax]="sometxt">{{ sometxt }}</div>
and in your .ts
sometxt: string = "$$someLatex"
Hope, this will help someone

What do I need to convert my Angular2 component to ES6 syntax?

index.js
Here is my entry point
import * as stylesheet from '../assets/styles/app.scss';
import jQuery from '../node_modules/jquery/dist/jquery';
import $ from '../node_modules/jquery/dist/jquery';
import {bootstrap} from './boot'
import {AppComponent} from './app.component'
bootstrap(AppComponent);
app.component.js
This works
(function (app) {
app.AppComponent = ng.core
.Component({
selector: 'my-app',
template: '<h1>My First Angular 2 App</h1>'
})
.Class({
constructor: function () {
}
});
})(window.app || (window.app = {}));
Question
I tried to use answer from How do I write angular2 without decorator syntax? without success.
How do I get rid of the IIFE and use ES6 syntax?
Untested!
import {Component} from 'angular2/core';
#Component({
selector: 'my-app',
template: `
<h1>
My First Angular 2 App
</h1>
`
})
export class AppComponent {
constructor () {
}
}
Perhaps you got a little confused by thinking you needed the app variable?
Just to be clear you don't need to reference app, you just need to import AppComponent (as you already have)
If you are using Babel and use the following plugins: 'angular2-annotations', 'transform-decorators-legacy', 'transform-class-properties', 'transform-flow-strip-types' there is no need to convert the syntax.
You can check it also in a working example.