coder-mike / microvium

A compact, embeddable scripting engine for applications and microcontrollers for executing programs written in a subset of the JavaScript language.
MIT License
568 stars 25 forks source link

Typescript scripts #83

Open Voxar opened 3 weeks ago

Voxar commented 3 weeks ago

Hi there!

We are looking around for typed scripting languages to run on our devices.

I experimented a bit with typescript and running it through tsc before microvium, but I'm not very experineces around js/ts/node etc so I'm not sure how to handle for example vmImport and vmExport.

Is there some magic ready to use or do you have throughts to share on how one could (or if one even should) approach a .ts -> .mvm-bc build flow?

Thanks.

coder-mike commented 2 weeks ago

Hi @Voxar

For TypeScript, you should be able to create a global.d.ts file with the following:

declare function vmExport(id: number, handler: Function): void;
declare function vmImport(id: number): Function;

This just tells TSC that these functions exist, so you don't get type errors when accessing them.

Something else to be aware of is that Microvium doesn't support commonjs, so your tsconfig should probably have a modern target and module field, such as ES2023 or ESNext, to avoid tsc rewriting the module imports to common.js.

Just for reference, in a Microvium project where I used TypeScript, I had something like the following scripts in package.json:

  "scripts": {
    "build": "npm run build:typescript && npm run build:microvium",
    "build:typescript": "tsc",
    "build:microvium": "microvium build/ts-output/main.js --snapshot build/app.mvm-bc --output-disassembly build/app.map
  },

and my tsconfig.json had "outDir": "./build/ts-output"

Let me know how this goes. What's the project you're working on?