How can I run JavaScript in Dart? - javascript

Dart officially provides JavaScript language support through the Dart web platform but for projects not using the web platform, there's unofficial support through a project called JSParser.
Due to my unfamiliarity with the language combined with sparse documentation, I'm not sure how to use this JSParser library. The example looks like this:
import 'package:parsejs/parsejs.dart';
void main() {
new File('test.js').readAsString().then((String code) {
Program ast = parsejs(code, filename: 'test.js')
// Use the AST for something
})
}
After installing the ParseJS library, the above code compiles just fine. But how do I interact with "the AST"? The IDE's code hinting doesn't seem to help either.
Looking back on the history of this project, it seems to have exchanged hands multiple times however all seem to be missing an example of what is done with the ast object afterward.
2014 - 2017: Managed by asgerf/parsejs.dart
2019 - 2019: Managed by anuragvohraec/parsejs.dart
2020 - 2020: Forked by ELEOS-MAP/parsejs.dart
2019 - 2019: A fork from a fork by anuragvohraec/dartJSEngine
Steps I've done:
Installed flutter
Installed and configured IntelliJ to use the flutter runtime I've installed
Installed the beta Desktop support for flutter
Installed the library and try to run the example
Are these libraries too old or am I just using them wrong? How would I know? I'm on Dart 2.11

After combining a few examples, notably this GitHub project and this unit test, I can get the interpreter to work.
dependencies:
dartjsengine: ^1.0.1
jsparser: ^2.0.1
Note, this uses JSEngine().visitProgram(...) combined with the parsejs() function from JSParser.
import 'package:dartjsengine/dartjsengine.dart';
import 'package:jsparser/jsparser.dart';
main() {
JsObject myObj = JSEngine().visitProgram(parsejs('var a = "red"; var b = "blue"; print(a); b;', filename: 'ignore'));
print('${myObj?.valueOf}');
}
Outputs:
red
blue
Some major caveats:
There's no alias from print() -> console.log(...), so the example uses the undocumented print(...) (aliased from Dart I guess?)
Several language features seem to be missing, importing an existing file as-is likely to fail.

Related

IntelliJ Angular Project with Kotlin/JS Library?

I have a library of Java code from Android development and I'd like to reuse that in a web-app version of the same. The library code is quite generic as it was always intended to be re-usable and has, in the past, been used to generate Android/Java, App-Engine/Java, iOS/ObjC, and GWT apps.
Looking around, I think the best framework for the web app would be Angular. Rewriting the library code to Kotlin should be a relatively minor task as there are tools to do most of the work. Then it can be compiled for the JVM (for native and backend apps) or JavaScript (for web apps).
While advice for/against this plan is welcome, my actual question is...
How do I set up an IntelliJ project to do this?
I thought the obvious answer would be two modules: one for the lib and one for the app but IntelliJ doesn't allow creating a Kotlin module, only a Kotlin project.
Instead, I made a Kotlin/JS project and used Angular/CLI to create the app module beneath it (with a backend app to sit beside it sometime in the future). The library builds and the sample app runs but I haven't been able to get the latter to include the generated JS (plus .d.ts) code of the former which sits in some deep directory under build/. So maybe I'm going about it all wrong...
Wow, that was rough! After many hours of Google searches and attempts that failed, here is something that works. Perhaps I'll find cleaner methods down the road but this is acceptable for now.
Note: I wasted too much time on gradle plugins for my liking. If they're not first-party, they tend to be unmaintained, poorly documented (largely assuming that the reader already knows what they're doing), and out of date. What follows is done only with first-party support programs.
Create a top-level project with Angular/CLI followed by sub-projects for the app and library:
ng new MyGeneralProject --no-create-application
ng generate library klib
ng generate application MyApp
Now set up Gradle in the top-level directory (or wait and do this via the IDE):
gradle init
gradle wrapper
Open the top-level in IntelliJ. Create/edit the top-level build.gradle.kts file:
buildscript {}
plugins {}
repositories {}
More important is the top-level settings.gradle.kts file:
rootProject.name = "MyProject"
include("projects:klib")
This will now access the projects/klib/gradle.build.kts file:
plugins {
kotlin("js") version "1.8.0"
}
repositories {
mavenCentral()
}
dependencies {
implementation(kotlin("stdlib-js"))
testImplementation(kotlin("test-js"))
}
kotlin {
sourceSets {
all {
// allow #JsExport without opt-in each time
languageSettings.optIn("kotlin.js.ExperimentalJsExport")
}
val main by getting {
kotlin.srcDir("src/main")
}
val test by getting {
kotlin.srcDir("src/test")
dependencies {
implementation(kotlin("test"))
}
}
}
js(IR) {
moduleName = "klib"
browser {
distribution {
directory = File("$projectDir/../../dist/$moduleName")
}
}
binaries.library()
}
}
The above uses the kotlin("js") plugin for Gradle but that's provided by JetBrains as part of IntelliJ who also maintain the Kotlin language libraries. Though the documentation for it also assumes you already know everything about Gradle, it nonetheless works just fine.
The built JS/TS library will be created under the top-level directory as "dist/klib". This naming could use some improvement but it's a reasonable starting point.
In the top-level tsconfig.json file, under "compilerOptions", look for "paths" and update as desired. I went with a leading "#" to indicate a top-level import location:
{
...
"compilerOptions": {
...
"paths": {
"#klib": [
"dist/klib"
]
}
...
},
...
}
In the projects/myapp/src/app/whatever.ts file, access the converted Kotlin library:
import * as klib from '#klib'
Then the entire library is available as klib.blah.blah.blah with IntelliJ providing full completion semantics.
2023-02-07: I've found that while this approach worked okay for creating the desired Angular project, it fell apart when trying to add a jvm-based backend with which it shared code. Now trying a different tactic...

Azure Functions bundle and extension, functions versions - javascript confusion 2.x, 5.0.x+?

I am making an azure cloudfunction with nodejs that gets triggered by a servicebus topic.
Reading this I am super confused, they have a version for everything and nothing makes sense in their documentation.
https://learn.microsoft.com/en-us/azure/azure-functions/functions-versions?tabs=in-process%2Cazure-cli%2Cv4&pivots=programming-language-javascript
The host.json file has 2 versions, the schema version and the bundle range version. Then the article talks about 5.x+ version, but the default range is 3.3.0 to 4.0 but not including 4. I am very confused what version am I using, what binding options are available to me and none of the articles explain anything in a clear and concise manner.
{
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[3.3.0, 4.0.0)"
}
}
Does this include 5.x+ that they talk about here? Do I need to make this 5.0.0?
If I use the host above, does this host.json config become invalid? The link above does not show messageHandlerOptions as one of the options (for 5.0.x) but mentions it being ok if not using sessions. Does it only apply for 2.0.x?
{
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[3.3.0, 4.0.0)"
},
"extensions": {
"serviceBus": {
"prefetchCount": 1,
"messageHandlerOptions": {
"autoComplete": true,
"maxConcurrentCalls": 1,
"maxAutoRenewDuration": "00:09:30"
}
}
},
"functionTimeout": "00:09:55"
}
What is the difference between Function and Extension?
I believe that my answer (below) solves your confusion:
Then the article talks about 5.x+ version, but the default range is 3.3.0 to 4.0 but not including 4. I am very confused what version am I using, what binding options are available to me
I think, they have given clarity/information about which host.json version to use in C# Programming language and missed that info in other languages in the same documentation.
If you take a closer look by minimizing the documentation to certain extent, then this will provide the clarity on extension versions:
Explanation:
If you use the version 5.x or later of this extension Microsoft.Azure.WebJobs.Extensions.ServiceBus, then you can use the new configuration settings available in Extension 5.x+ in the host.json file.
If you use the version <5.x of this extension Microsoft.Azure.WebJobs.Extensions.ServiceBus, then can use the configurable settings available in Function 2.x+ in the host.json file.
What is the difference between Function and Extension?
AFAIK, they renamed the version name as Function 1.x, 2.x, Extension 5.x which are stable versions.
If I use the host above, does this host.json config become invalid? The link above does not show messageHandlerOptions as one of the options (for 5.0.x) but mentions it being ok if not using sessions. Does it only apply for 2.0.x?
As per my understanding - in the documentation, they have new configuration settings available of each version but the messageHandlerOptions is available in both the Function 2.x and Extension 5.x versions of the host.json file in Azure Functions Service Bus Trigger Bindings.
Updated Answer:
The MSFT Doc you have provided in the comment gives the details about Azure Functions Runtime Versions like 1.x, 2.x, 3.x and 4.x.
These are the Azure Functions Core Tools Versions required to run the specific language runtime programs.
For example:
JavaScript Versions (NodeJS 10, 12 & 14) works good with the Azure Functions Version 3.x whereas NodeJS version 16 works good with the Azure Functions Version 4.x.
This document also described the Migration steps and breaking changes of Azure Functions Runtime/Core Tools versions from old version to newer version.
Do I change the range in host.json to 5?
Every version of host.json i.e, Functions 1.x, Functions 2.x and Extension 5.x are same, they have incremented/discovered new configurable settings in each newer version.
I still don't understand the difference between function version and extension version. What version am I running?
Refer to Explanation Para in the same answer.
In a Simple, if you're using the extension Microsoft.Azure.WebJobs.Extensions.ServiceBus version is equal to 5.x or later, then you can use the settings available in Extensions 5.x+ block. If that ServiceBus extension version is less than 5.x, then use the configuration settings available in Functions 2.x for the host.json file.

Attempted import errors in react-native-web monorepo architecture

Hi there,
I am following this article to setup a react-native + web code sharing. Here is the repo link with bare-bone monorepo setup as described in above article.
I successfully did setup bare-bone monorepo app as described in above article, than i ported my existing react-native app code to this architecture(in the components folder) and got mobile app working and everything.
I am getting some errors when i try to run web app(which used react-native-web to convert react-native to web). Its not that i was not expecting some errors, i know react-native-web is yet not that stable and not that up to date for react-native version above 0.55 and all those gotchas.
But the errors i am getting here are more related to my webpack config i think. My config-override.js file is basically the same as original one except this part(which i changed in a hope to get through the errors i will mention below):
const appIncludes = [
resolveApp('src'),
resolveApp('../components/src'),
resolveApp('../../node_modules/react-navigation-deprecated-tab-navigator'),
resolveApp('../../node_modules/react-native-color-matrix-image-filters'),
resolveApp('../../node_modules/react-native-htmlview'),
resolveApp('../../node_modules/react-native-loading-spinner-overlay'),
resolveApp('../../node_modules/#react-native-community/async-storage'),
resolveApp('../../node_modules/react-native-cookies'),
resolveApp('../../node_modules/react-native-router-flux'),
resolveApp('../../node_modules/react-native-actionsheet'),
resolveApp('../../node_modules/react-native-autocomplete-input'),
resolveApp('../../node_modules/react-native-circular-progress'),
resolveApp('../../node_modules/react-native-google-places-autocomplete'),
resolveApp('../../node_modules/react-native-image-progress'),
resolveApp('../../node_modules/react-native-image-zoom-viewer'),
resolveApp('../../node_modules/react-native-image-pan-zoom'),
resolveApp('../../node_modules/react-native-keyboard-aware-scroll-view'),
resolveApp('../../node_modules/react-native-linear-gradient'),
resolveApp('../../node_modules/react-native-permissions'),
resolveApp('../../node_modules/react-native-phone-input'),
resolveApp('../../node_modules/react-native-picker-select'),
resolveApp('../../node_modules/react-native-progress'),
resolveApp('../../node_modules/react-native-push-notification'),
resolveApp('../../node_modules/react-native-snap-carousel'),
resolveApp('../../node_modules/react-native-svg'),
resolveApp('../../node_modules/react-native-tab-view'),
resolveApp('../../node_modules/react-navigation-drawer'),
resolveApp('../../node_modules/react-navigation-stack'),
resolveApp('../../node_modules/react-native-screens'),
resolveApp('../../node_modules/react-navigation-tabs'),
resolveApp('../../node_modules/#react-navigation'),
resolveApp('../../node_modules/react-native-router-flux'),
resolveApp('../../node_modules/react-native-gesture-handler'),
resolveApp('../../node_modules/react-navigation'),
]
Couple or errors i am getting on yarn workspace web start are:
import {
Grayscale
} from 'react-native-color-matrix-image-filters';
It gives:
Attempted import error: 'Grayscale' is not exported from
'react-native-color-matrix-image-filters'.
If i just remove this import and its use, i than get:
Attempted import error: 'react-native-cookies' does not contain a
default export (imported as 'CookieManager').
On:
import CookieManager from 'react-native-cookies';
While playing around, i also got:
...../node_modules/react-native-router-flux/src/navigationStore.js
Attempted import error: 'TabBarBottom' is not exported from 'react-navigation-deprecated-tab-navigator' (imported as 'DEPRECATED_TabBarBottom').
I am pretty sure this is something wrong with my webpack/babel config(config-override.js file). And i certainly know i will get more errors after resolving these. And this setup might end up not working at all for us. But it worths a try and i must be able to get through these errors with your help.
Thanks.
You can probably not use these packages on the web since they're react native packages (Android and iOS) and not web packages.
Which means that you have to split the files that import and use these packages.
Example of creating a wrapper for CookieManager: cookieManagerWrapper.js(everything else: Android and iOS) and cookieManagerWrapper.web.js(Web only).
In the web specific js file, you don't import CookieManager but import an alternative web library instead to implement the same functionality as on mobile but with different code that works on the web.
Then you can import and use cookieManagerWrapper.js everywhere and react-native-web will automatically substitute it with the cookieManagerWrapper.web.js when available.
Some react native packages do work on web too when they're only consisting of platform independent JavaScript code. Also some packages have web implementations that can be aliased in webpack like react-native-gradients with react-native-web-gradients, sadly this is not the case with the packages mentioned in the question.
This file splitting with file.js, file.web.js, file.android.js and file.ios.js makes it possible to write different implementations for each platform. This is also great for some user interface code, you can use 3rd party react components on the web and 3rd party react native components on mobile that look similar to implement more complex user interactions since react native web supports all regular react code and jsx tags on the web.
I was able to get past this error by adding:
config.module.strictExportPresence = false in the config-override.js
Now i am stuck on further issues.
Original issue in the question is gone by this. I will post with any other related updates if i have any.

How to call a javascript type="module" from a webpage? [duplicate]

I am currently writing a web application using the MEAN Stack, and am attempting to write code in ECMAScript 6 JavaScript; however, I am getting errors in both Chrome and Firefox when using import and export syntax. Are there currently any browsers that fully support ECMAScript 6?
Please note: I am not asking when ECMAScript 6 will be supported by browsers. I'm asking which browsers support ECMAScript 6 import and export syntax. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_6_support_in_Mozilla#Features_not_yet_supported_by_Firefox
It's supported in:
Safari 10.1
Chrome 61
Firefox 54 – behind the dom.moduleScripts.enabled setting in about:config.
Edge 16
Chrome and Firefox support import and export syntax (there exists tests for proper parsing).
What isn't supported is module loading - you can't load module by any means, because specification for it isn't complete. You have to use some kind of module bundler for this. I'm not front-end developer, but I have heard good opinions on Rollup from my coworkers.
As others have said, support for it is still very limited. But even if there was full support.... would it be smart to use it? How would we do that?
Think about it. A typical JS app written with Node JS modules easily contains dozens, even hundreds of (very small) packages. Do we really want that many requests?
Browserify, Webpack, Rollup etc are so popular because they allow us to bundle many small packages into one fast download. With code splitting we can let the module bundler decide at transpilation time, based on the code our pages are actually using and on some configuration settings, how many bundles to create and what to put in each of them. That way we can write many small packages and serve them as a (couple of) big bundles.
My point is that we should divide our code into packages that work well on a conceptual level, then bundle those packages into bundles that work well on a technical (network) level. If we write our code based on optimum network packet size, we end up sacrificing modularity in the process.
In the meantime, using it will probably only add to the confusion. For example, look at the example on the Edge blog:
import { sum } from './math.js';
Note how they add the extension .js to the from string? In Node JS we usually write this as:
import { sum } from './math';
So will the above code also work on Edge? And what about named packages? I fear we will see a lot of incompatibility here before we figure out how to make these paths work across the board.
I would hazard to guess that for most developers, System.import will remain mostly invisible in the browsers and that only the bundling software itself will start to use it (for efficiency purposes) when it becomes mainstream.
Now there's a pollyfill that you can use to import ES6 module.
I tested it successfully on Chrome.
Here is the link: http://github.com/ModuleLoader/browser-es-module-loader
It is also implemented natively in Edge 14:
https://blogs.windows.com/msedgedev/2016/05/17/es6-modules-and-beyond
According to Google's Javascript Style Guide:
Do not use ES6 modules yet (i.e. the export and import keywords),
as their semantics are not yet finalized. Note that this policy will
be revisited once the semantics are fully-standard.
// Don't do this kind of thing yet:
//------ lib.js ------
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
//------ main.js ------
import { square, diag } from 'lib';
However, import and export are implemented in many transpilers, such as the Traceur Compiler, Babel or Rollup.

V8 JavaScript Engine on Windows (MinGW)

The build instructions of V8 JavaScript Engine mention only Visual Studio 2005 and 2008. Has anybody been successful with MinGW on Windows XP/Vista?
You just need to change Scons a bit.
Take a look at C:\YourPythonFolder\Lib\site-packages\scons-YourSconsVersion\SCons\Script__ init__.py and go to line 560.
Change the linker to gnulink, the c compiler to mingw and the c++ compiler to g++.
Eventually it should look like this:
linkers = ['gnulink', 'mslink', 'ilink', 'linkloc', 'ilink32' ]
c_compilers = ['mingw', 'msvc', 'gcc', 'intelc', 'icl', 'icc', 'cc', 'bcc32' ]
cxx_compilers = ['g++', 'msvc', 'intelc', 'icc', 'c++', 'bcc32' ]
Now MingW is activated by default :)
There is a patch for MinGW support: http://codereview.chromium.org/18309
See also:
http://code.google.com/p/v8/issues/detail?id=64
I've tried, but seems it automatically detect the WIN32 platform and tries to invoke the vc++ compiler, I tried to adding to the PATH the mingw-gcc compiler (I've not vc++ installed) and the build script correctly sees it, but doesn't compile out of the box.
I suppose deleting the "WIN32 flag" will do the work, since for successfully compiling under mingw the compiler needs to thinks to be on unix enviroment, but then even if it compiles probably it will have some problems due to the different platform.
V8 seems to use different parts of its code (especialy for the file system stuff) for different platforms.
I made a build under Cygwin which puts out a beautiful linux lib, which runs on linux but doesn't on Win. I think partwise this will be the same with MinGW if you erase the WIN32 flag!
At the moment I just can see 2 possibilities. One is simple: Use Visual Studio, it's free.
The second is very hard: write a makefile :)

Categories