패키지, 저장소 및 앱 카테고리 검색

패키지 상세v0.3.7

flutter_qjs

이 플러그인은 `quickjs` 프로젝트를 사용하여 플러터용 간단한 JS 엔진입니다. 현재 웹을 제외한 모든 플랫폼을 지원합니다!

30일 다운로드
194
좋아요
31
Pub 점수
60

패키지 설치

flutter pub add flutter_qjs

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

flutter_qjs는 Dart 애플리케이션이 네이티브로 JavaScript 코드를 실행할 수 있도록 해주는 Flutter 플러그인입니다. 웹을 제외한 모든 주요 플랫폼을 지원하며, 경량의 내장 스크립팅이 필요한 시나리오에 이상적입니다. 이 플러그인은 JS 표현식 평가, 함수 호출, Dart와 JavaScript 간 데이터 교환을 위한 간단한 API를 제공합니다. 고성능 QuickJS 프로젝트 기반으로 구축되어 최소한의 오버헤드로 빠른 실행을 보장합니다. 동적 로직, 구성 스크립트 또는 재컴파일 없이 앱 기능을 확장하는 데 적합합니다.

사용 사례

  • 앱에서 동적 스크립트 실행
  • 자바스크립트 로직 삽입
  • 런타임 시 앱 동작 확장
  • 스크립트를 통해 앱 기능 구성하기
  • 레거시 JS 코드와의 인터페이스

주요 기능

  • 경량 QuickJS 엔진
  • 다중 플랫폼(웹 제외)
  • Dart-JS 상호 운용성
  • 스크립트 평가를 위한 간단한 API
  • 낮은 메모리 사용량으로 빠른 실행

적합한 대상

  • 동적 스크립트가 필요한 앱
  • 논리 처리에 JS를 사용하는 개발자
  • 내장 엔진이 필요한 플러그인
  • 스크립터블 컴포넌트를 사용한 프로토타이핑
  • 웹이 아닌 모바일 및 데스크톱 앱

고려 사항

  • 웹 플랫폼에서 사용할 수 없습니다
  • QuickJS 전용 JS 기능에 한정
  • 주의 깊은 오류 처리가 필요합니다
  • 앱 크기가 약간 증가할 수 있습니다
  • 현대적인 ES 모듈을 지원하지 않습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

flutter_qjs

Pub Test

English | 中文

This plugin is a simple js engine for flutter using the quickjs project with dart:ffi. Plugin currently supports all the platforms except web!

Getting Started

Basic usage

Firstly, create a FlutterQjs object, then call dispatch to establish event loop:

final engine = FlutterQjs(
  stackSize: 1024 * 1024, // change stack size here.
);
engine.dispatch();

Use evaluate method to run js script, it runs synchronously, you can use await to resolve Promise:

try {
  print(engine.evaluate(code ?? ''));
} catch (e) {
  print(e.toString());
}

Method close can destroy quickjs runtime that can be recreated again if you call evaluate. Parameter port should be close to stop dispatch loop when you do not need it. Reference leak exception will be thrown since v0.3.3

try {
  engine.port.close(); // stop dispatch loop
  engine.close();      // close engine
} on JSError catch(e) { 
  print(e);            // catch reference leak exception
}
engine = null;

Data conversion between dart and js are implemented as follow:

dart js
Bool boolean
Int number
Double number
String string
Uint8List ArrayBuffer
List Array
Map Object
Function(arg1, arg2, ..., {thisVal})
JSInvokable.invoke([arg1, arg2, ...], thisVal)
function.call(thisVal, arg1, arg2, ...)
Future Promise
JSError Error
Object DartObject

Use Modules

ES6 module with import function is supported and can be managed in dart with moduleHandler:

final engine = FlutterQjs(
  moduleHandler: (String module) {
    if(module == "hello")
      return "export default (name) => `hello \${name}!`;";
    throw Exception("Module Not found");
  },
);

then in JavaScript, import function is used to get modules:

import("hello").then(({default: greet}) => greet("world"));

notice: Module handler should be called only once for each module name. To reset the module cache, call FlutterQjs.close then evaluate again.

To use async function in module handler, try run on isolate thread

Run on Isolate Thread

Create a IsolateQjs object, pass handlers to resolving modules. Async function such as rootBundle.loadString can be used now to get modules:

final engine = IsolateQjs(
  moduleHandler: (String module) async {
    return await rootBundle.loadString(
        "js/" + module.replaceFirst(new RegExp(r".js$"), "") + ".js");
  },
);
// not need engine.dispatch();

Same as run on main thread, use evaluate to run js script. In isolate, everything returns asynchronously, use await to get the result:

try {
  print(await engine.evaluate(code ?? ''));
} catch (e) {
  print(e.toString());
}

Method close can destroy isolate thread that will be recreated again if you call evaluate.

Use Dart Function (Breaking change in v0.3.0)

Js script returning function will be converted to JSInvokable. It does not extend Function, use invoke method to invoke it:

(func as JSInvokable).invoke([arg1, arg2], thisVal);

notice: evaluation returning JSInvokable may cause reference leak. You should manually call free to release JS reference.

(obj as JSRef).free();
// or JSRef.freeRecursive(obj);

Arguments passed into JSInvokable will be freed automatically. Use dup to keep the reference.

(obj as JSRef).dup();
// or JSRef.dupRecursive(obj);

Since v0.3.0, you can pass a function to JSInvokable arguments, and channel function is no longer included by default. You can use js function to set dart object globally. For example, use Dio to implement http in qjs:

final setToGlobalObject = await engine.evaluate("(key, val) => { this[key] = val; }");
await setToGlobalObject.invoke(["http", (String url) {
  return Dio().get(url).then((response) => response.data);
}]);
setToGlobalObject.free();

In isolate, top level function passed in JSInvokable will be invoked in isolate thread. Use IsolateFunction to pass a instant function:

await setToGlobalObject.invoke([
  "http",
  IsolateFunction((String url) {
    return Dio().get(url).then((response) => response.data);
  }),
]);

카테고리

의존성

의존성 목록 1 개

소스 저장소

이 패키지를 사용하는 프로젝트