Babel ie8 new ClassName throw 'Cannot call a class as a function' - babeljs

Ive tried multiple variations of this, but none of them seem to work. Any ideas?
webpack.config.js:
{
test: /\.js[x]?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['es2015-loose', 'stage-0'],
cacheDirectory: true,
//cacheIdentifier : '.babelrc',
plugins: ['transform-runtime']
}
}
js code :
import "babel-polyfill";
class CC{
constructor(x, y) {
this.x = x;
this.y = y;
}
}
var c1 = new CC(1,2);
Thanks in advance.

Related

vscode extension is it possible to pass args into a command markdown link?

I'm working on a vscode extension using the HoverProvider to supply some HTML links for the MarkdownString, the links themselves are my own commands that work fine (they are being registered and their function hits). Unfortunately I'm unable to pass any querystring values/arguments into the command function.
Is it possible to pass args via the MarkdownString so that the command function receives them?
package.json
{
"name": "hover-command",
.. snip snip ...
"contributes": {
"commands": [
{
"command": "hover-command.say_hello",
"title": "greetz"
}
]
},
In the extension.ts file
context.subscriptions.push(
vscode.commands.registerCommand("say_hello", async (hi: string) => {
vscode.window.showInformationMessage(hi + ' greetz at ' + new Date());
})
);
and
const selector: vscode.DocumentSelector = {
scheme: "file",
language: "*",
};
vscode.languages.registerHoverProvider(selector, {
provideHover(
doc: vscode.TextDocument,
pos: vscode.Position,
token: vscode.CancellationToken
): vscode.ProviderResult<vscode.Hover> {
return new Promise<vscode.Hover>((resolve, reject) => {
const hoverMarkup = "[Greetings...](command:say_hello?hi=world)";
if (hoverMarkup) {
const mdstring = new vscode.MarkdownString(hoverMarkup);
mdstring.isTrusted = true; // NOTE: this is needed to execute commands!!
resolve(new vscode.Hover(mdstring));
} else {
reject();
}
}
);
},
});
but the registered command vscode.window.showInformationMessage is not getting any arguments/query string values. I have tried looking at arguments but still at a loss.
A few examples from the VSC source code
[search the Marketplace](command:workbench.extensions.search?%22%40category%3A%5C%22scm%20providers%5C%22%22)
[Initialize Repository](command:git.init?%5Btrue%5D)
[configure](command:workbench.action.openSettings?%5B%22editor.formatOnSave%22%5D)
Thanks again #rioV8, after a few failed attempts there are a few steps to get command hover markdown links to work with arguments.
I'm using TypeScript, so I'll add an interface to define the shape of the args
interface ISayHelloArgs {
msg: string;
}
The registered command then uses this interface (you get a single object 'args')
context.subscriptions.push(
vscode.commands.registerCommand("say_hello", async (args: ISayHelloArgs) => {
vscode.window.showInformationMessage(args.msg + ' greetz at ' + new Date());
})
);
The registered HoverProvider then build the args using encodeURI version of a JSON string.
vscode.languages.registerHoverProvider(selector, {
provideHover(
doc: vscode.TextDocument,
pos: vscode.Position,
token: vscode.CancellationToken
): vscode.ProviderResult<vscode.Hover> {
return new Promise<vscode.Hover>((resolve, reject) => {
const args: ISayHelloArgs = { msg: 'hello' };
const jsonArgs = JSON.stringify(args);
const hoverMarkup = `[Greetings...](command:say_hello?${encodeURI(jsonArgs)})`;
if (hoverMarkup) {
const mdstring = new vscode.MarkdownString(hoverMarkup);
mdstring.isTrusted = true; // NOTE: this is needed to execute commands!!
resolve(new vscode.Hover(mdstring));
} else {
reject();
}
}
);
},
});
This worked for me, hope it helps others.

Use vue3-cookies in custom plugin

I want to use vue3-cookies in my custom plugin, but whatever I do I keep getting undefined.
MyPlugin.js
export default {
install: (app, options) => {
app.config.globalProperties.$MyPlugin= {
someFunction() {
console.log(app.cookie);
console.log(app.cookies);
console.log(app.$cookies);
}
}
},
};
app.js
import {createApp} from 'vue';
import VueCookies from 'vue3-cookies'
import MyPlugin from "./plugins/MyPlugin";
const app = createApp({});
app.use(VueCookies)
app.use(MyPlugin)
const mountedApp = app.mount('#app');
What am I missing or doing wrong?
OK, I clearly missed a piece while reading the documentation.
This did the trick.
https://github.com/KanHarI/vue3-cookies#usage---via-composition-api-recommended
import {useCookies} from "vue3-cookies";
export default {
install: (app, options) => {
app.config.globalProperties.$MyPlugin = {
someFunction() {
const {cookies} = useCookies();
console.log(cookies.get('cookie_name'));
}
}
},
};

Some errors with getting #:genericbuild working (haxe nightly)

Now Solved
This post is a follow up on a previous post
I have taken example code with #:genericbuild which runs ok and modified it, but then it doesn't run.
While I am not new to haxe I am totally new when it comes to macro's. I am used to thoroughly look in documentation and even code if documentation is hard to find. But with haxe macro's that isn't so easy, that's why I hope to find some answers here. With those answers I hope to gain knowledge so I can help improving haxe documentation, so others new to macro's have an easier time.
I have studied documentation available and code.
There are 3 files. The file with driver code (Main.hx), a parameterised enum being generated by a macro(Either.hx) making use of #:genericbuild and the macro file that generates that file (EitherBuildMacro.hx).
I have the latest haxe nightly running. I copied some code of a library that uses genericbuild and runs on my computer. This I will call "reference code" from now on. But when I run the copied and modified above 3 files, I get the error messages:
1) 'Invalid number of type parameters for shl.ds.Either'
2) 'Enum> has no field _1'
It appears the macro can not be executed, also due to errors. It seems the library code which I took as an example doesnt run as an initialization macro, but as a build macro. This is probably the part where I am getting things wrong.
There are also errors about the macrofile (EitherBuildMacro.hx)
1) 'Class has no field defineType'
2) 'Class has no field currentPos'
When I look to the reference code, there all these fields do exist.
Main.hx
class Main{
public static function main(){
var a:Either<String,Int>=Either._1('test'); //<--------
var b:Either<String,Int>=Either._2(123); //<--------
}
}
Either.hx
package shl.ds;
#:genericBuild(shl.macros.build.EitherBuildMacro.build()) //<--------
enum Either<Rest> {} //<--------
EitherBuildMacro.hx
import haxe.macro.Context;
import haxe.macro.Expr;
import haxe.macro.Type;
using haxe.macro.Tools;
class EitherBuildMacro {
public static function build() {
for (i in 2...11) {
Context.defineType({ //<--------
pack: [],
name: "Either" + i,
pos: Context.currentPos(), //<--------
kind: TDEnum,
fields: [
for (j in 0...i) {
name: "_" + (j + 1),
kind: FFun({
args: [
{
name: "value",
type: TPath({
name: String.fromCharCode(65 + j),
pack: []
})
}
],
ret: null,
expr: null
}),
pos: Context.currentPos()
}
],
params: [
for (j in 0...i) {
name: String.fromCharCode(65 + j)
}
]
});
}
}
}
The reference code you can find here (https://gist.github.com/nadako/b086569b9fffb759a1b5)
This is the code I took as inspiration
Signal.hx
#:genericBuild(SignalMacro.build())
class Signal<Rest> {} //<--------
SignalMacro.hx
import haxe.macro.Context;
import haxe.macro.Expr;
import haxe.macro.Type;
using haxe.macro.Tools;
class SignalMacro {
static var signalTypes = new Map<Int,Bool>();
static function build():ComplexType {
return switch (Context.getLocalType()) {
case TInst(_.get() => {name: "Signal"}, params):
buildSignalClass(params);
default:
throw false;
}
}
static function buildSignalClass(params:Array<Type>):ComplexType {
var numParams = params.length;
var name = 'Signal$numParams';
if (!signalTypes.exists(numParams))
{
var typeParams:Array<TypeParamDecl> = [];
var superClassFunctionArgs:Array<ComplexType> = [];
var dispatchArgs:Array<FunctionArg> = [];
var listenerCallParams:Array<Expr> = [];
for (i in 0...numParams) {
typeParams.push({name: 'T$i'});
superClassFunctionArgs.push(TPath({name: 'T$i', pack: []}));
dispatchArgs.push({name: 'arg$i', type: TPath({name: 'T$i', pack: []})});
listenerCallParams.push(macro $i{'arg$i'});
}
var pos = Context.currentPos(); //<--------
Context.defineType({ //<--------
pack: [],
name: name,
pos: pos,
params: typeParams,
kind: TDClass({
pack: [],
name: "Signal",
sub: "SignalBase",
params: [TPType(TFunction(superClassFunctionArgs, macro : Void))]
}),
fields: [
{
name: "dispatch",
access: [APublic],
pos: pos,
kind: FFun({
args: dispatchArgs,
ret: macro : Void,
expr: macro {
startDispatch();
var conn = head;
while (conn != null) {
conn.listener($a{listenerCallParams});
if (conn.once)
conn.dispose();
conn = conn.next;
}
endDispatch();
}
})
}
]
});
signalTypes[numParams] = true;
}
return TPath({pack: [], name: name, params: [for (t in params) TPType(t.toComplexType())]});
}
}
And some test driver code
Main.hx
class Main {
static function main() {
var signal = new Signal<Int,String>(); //<--------
var conn = signal.connect(function(a, b) {
trace('Well done $a $b');
});
signal.dispatch(10, "lol");
}
}

The createClass helper of babeljs make mangle not working

I am using babel as transpiler and I want to mangle some methods with uglifyjs.
Here is a demo:
class A {
methodA() {}
}
And its output by babel:
var A = function () {
function A() {
_classCallCheck(this, A);
}
_createClass(A, [{
key: "methodA",
value: function methodA() {}
}]);
return A;
}();
However when I try to mangle methodA, it does not work. Because methodA in the output is a string.
But the same code output by typescript works, it is not a string:
var A = /** #class */ (function () {
function A() {
}
A.prototype.methodA = function () { };
return A;
}());
So my question is: How can I mangle method name when using babeljs ?
OK, I found the answer.
Just use loose mode:
[ ['#babel/preset-env', { loose: true }] ]
The result will be closer to TS.

How to use node-simple-schema reactively?

Given that there is not much examples about this, I am following the docs as best as I can, but the validation is not reactive.
I declare a schema :
import { Tracker } from 'meteor/tracker';
import SimpleSchema from 'simpl-schema';
export const modelSchema = new SimpleSchema({
foo: {
type: String,
custom() {
setTimeout(() => {
this.addValidationErrors([{ name: 'foo', type: 'notUnique' }]);
}, 100); // simulate async
return false;
}
}
}, {
tracker: Tracker
});
then I use this schema in my component :
export default class InventoryItemForm extends TrackerReact(Component) {
constructor(props) {
super(props);
this.validation = modelSchema.newContext();
this.state = {
isValid: this.validation.isValid()
};
}
...
render() {
...
const errors = this.validation._validationErrors;
return (
...
)
}
}
So, whenever I try to validate foo, the asynchronous' custom function is called, and the proper addValidationErrors function is called, but the component is never re-rendered when this.validation.isValid() is supposed to be false.
What am I missing?
There are actually two errors in your code. Firstly this.addValidationErrors cannot be used asynchronously inside custom validation, as it does not refer to the correct validation context. Secondly, TrackerReact only registers reactive data sources (such as .isValid) inside the render function, so it's not sufficient to only access _validationErrors in it. Thus to get it working you need to use a named validation context, and call isValid in the render function (or some other function called by it) like this:
in the validation
custom() {
setTimeout(() => {
modelSchema.namedContext().addValidationErrors([
{ name: 'foo', type: 'notUnique' }
]);
}, 100);
}
the component
export default class InventoryItemForm extends TrackerReact(Component) {
constructor(props) {
super(props);
this.validation = modelSchema.namedContext();
}
render() {
let errors = [];
if (!this.validation.isValid()) {
errors = this.validation._validationErrors;
}
return (
...
)
}
}
See more about asynchronous validation here.