Getting error while using Decorators in js - babeljs

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.

Related

How to add babel and polyfills to a RequireJs project?

I am working on a legacy project which uses RequireJs to load and resolve all the dependencies. It works fine on modern browsers, but i need to add support for IE11.
I tried to use babel 7 with #babel/preset-env with following .babelrc
{
"presets": [
["#babel/preset-env", {
"useBuiltIns": "usage",
"corejs": 3,
"targets": {
"browsers" : ["ie>=11"]
},
"modules": false
}]
],
"compact": false
}
the import statements injected by the preset as following
import "core-js/modules/es.function.name.js";
cause error "import statements can't be used outside a module". Even when I use modules: "amd", then core-js is imported as
define(["core-js/modules/es.array.filter.js", "core-js/modules/es.object.to-string.js", "core-js/modules/es.string.includes.js", "core-js/modules/es.function.name.js", "core-js/modules/es.regexp.exec.js", "core-js/modules/es.string.split.js", "core-js/modules/es.string.small.js", "core-js/modules/es.string.search.js"], function (_esArrayFilter, _esObjectToString, _esStringIncludes, _esFunctionName, _esRegexpExec, _esStringSplit, _esStringSmall, _esStringSearch) {
"use strict";
//...
});
which throws error like "define is not defined in require.js".
When using useBuiltIns: "entry", and then including core-js as
require(["core-js", ../other modules], function(corejs, ...){
}
)
in the main.js file, it fails to correctly resolve the path of the files even though I have included the path to core-js in require.config.paths.
I tried #babel/runtime and #babel/plugin-transform-runtime but no luck there.
So my question is what would be the best way to add babel and the required polyfills in my RequireJs project so that it is compatible with IE 11?

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();
}

Javascript in nuxt plugins folder - how to use in component?

I have a javascript variable (var testButton) in my Nuxt plugins folder. I then added the file to my nuxt.config.js plugins. In my component, I have a Buefy button, and I'm trying to call the script:
<b-button #click="testButton">Click Me</b-button>
...
<script>
export default {
mounted () {
this.$testButton()
}
}
</script>
I import the script in my script section and have tried computed and mounted lifecycles. Not sure what I'm doing wrong. Thank you
Check the following things, you must be missing one or more:
1. Your plugin should export a method. That method should receive an 'inject' function and use it to register your 'testButton' function.
So, in your ~/plugins/testButton.js
export default (context, inject) => {
inject('testButton', () => {
console.log('testButton works!')
})
}
2. You shuold register your plugin correctly in the nuxt.conf.js file
Do it like so:
plugins: [
{ src: '~/plugins/testButton.js' },
],
3. Call it as '$testButton()' (note that Nuxt will have added a dollar sign to your method's name).
Your '$testButton' method will now be available from anywhere in your nuxt app. You don't have to import it o create any computed property.
<b-button #click="$testButton">Click Me</b-button>
<script>
export default {
}
</script>

Can't import tween using import

I have an es6 script that include a tween library with es6 import. The code works fine if it's not transpiled, I mean I can import tween and use it inside the script, if I use webpacke with my configuration the script exit with an error becouse the TWEEN is somehow undefined.
I have tried change extension of tween file with mjs but it generate other errors like
require is not defined
I webpack add core-js modules using require funcition
require("core-js/modules/es.symbol");
The code with issue
'use strict';
...
import {TWEEN} from '../threejs/tween.js';
//import {TWEEN} from '../threejs/tween.js';
...
export class CustomClass extends ParentClass {
constructor(arguments) {
super(arguments);
this.tweenGroup = new TWEEN.Group(); // the line that generate "Cant get Group of undefined"
}
...
}
...
this is my babel-loader configuration configuration
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
sourceType: 'module'
}
}
},
my babel configuration is look like this
module.exports = {
presets: [
[
'#babel/preset-env',
{
debug: true,
useBuiltIns: 'usage',
corejs: 3
}
]
],
plugins: [
// '#babel/plugin-proposal-class-properties',
// '#babel/plugin-transform-runtime',
// '#babel/runtime-corejs2',
// '#babel/plugin-syntax-dynamic-import',
// '#babel/plugin-syntax-async-generators',
// '#babel/plugin-transform-regenerator',
// '#babel/plugin-transform-async-to-generator',
'#babel/plugin-transform-modules-commonjs',
// '#babel/plugin-transform-typeof-symbol'
]
};
The code with TWEEN import (the first block of code I posted) work just fine if I use it in a project that is not transpiled with babel, but it generate the error if I run devserver. I don't understand why I can't import the Tween properly afetr compilation.
I will apriciate any help.l
Update: I realized I had rather different setup and different issue than you did, but while searching the solution I found this thread with recommendation for npm intalling tween for babel workflow. Maybe that is helpful for you.
I still leave my initial reply here, could be useful for anyone else:
I had some trouble including TWEEN within my js project (eg using import * as TWEEN from '...'), but following the those steps for simple installation I got it working after I included it in HTML, not in js:
<script src="js/libs/Tween.js"></script>

How to use Angular2 and Typescript in Jsfiddle

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));