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

패키지 상세v1.2.1

jsf

Flutter에서 기본 제공되는 고성능 자바스크립트 엔진입니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
4.7천
좋아요
17
Pub 점수
160

패키지 설치

flutter pub add jsf

패키지 개요

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

jsf는 높은 성능을 갖춘 JavaScript 엔진으로, Flutter에 직접 통합되어 여러 플랫폼에서 JavaScript 코드를 원활하게 실행할 수 있게 해줍니다. 효율성과 사용 편의성을 고려해 설계되었으며, 외부 종속성 없이 Flutter 앱 내에서 JavaScript를 실행할 수 있도록 합니다. 완전한 JavaScript 상호 운용성을 지원하여 스크립트 삽입, 동적 로직 실행 또는 기존 JavaScript 라이브러리와의 통합에 이상적입니다. 실시간 스크립트 평가나 크로스플랫폼 호환성이 필요한 경우 특히 유용합니다. Android, iOS, Web, macOS, Windows, Linux를 지원하며, 다양한 환경에서 일관된 동작을 보장합니다.

사용 사례

  • Flutter 앱에서 동적 JavaScript 코드 실행
  • 레거시 자바스크립트 라이브러리 통합
  • 스크립트 가능한 UI 컴포넌트 활성화
  • 실시간 코드 평가
  • 크로스플랫폼 자바스크립트 실행

주요 기능

  • 고성능 자바스크립트 엔진
  • 네이티브 플러터 통합
  • 다중 플랫폼 지원 (Android, iOS, Web, macOS, Windows, Linux)
  • 무결점 자바스크립트 상호 운용성
  • 경량이며 빠른 시작

적합한 대상

  • Flutter에서 JavaScript 런타임이 필요한 개발자
  • 동적 스크립트가 필요한 앱
  • 기존 JS 라이브러리를 사용하는 프로젝트
  • 크로스플랫폼 애플리케이션
  • 성능에 민감한 환경

고려 사항

  • JavaScript 보안 위험에 대한 신중한 대응이 필요합니다
  • 앱 크기가 약간 증가할 수 있습니다
  • 네이티브 JS 환경에 비해 디버깅 도구가 제한적
  • 중량 서버 측 자바스크립트 작업 부하에 적합하지 않습니다

원본 README

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

JSF

English | 中文文档

A high-performance JavaScript engine available out of the box in Flutter.

Features

  1. Up-to-date QuickJS support.
  2. High-performance build strategy enabled by default.
  3. big number and related features enabled by default.
  4. Automatic type conversion with Dart and JavaScript interop.
  5. Full platform support, including Web and OHOS.

pic.png

Quick Start

import 'package:jsf/jsf.dart';

final js = JsRuntime();
print(js.eval('40 + 2')); // 42

Runtime Configuration

final js = JsRuntime(
  options: const JsRuntimeOptions(
    memoryLimitBytes: 64 * 1024 * 1024,
    maxStackSizeBytes: 1024 * 1024,
    timeout: Duration(seconds: 2),
  ),
);

timeout is enforced by QuickJS' interrupt handler. Clear or replace it with:

js.clearTimeout();
js.setTimeout(const Duration(milliseconds: 500));

Values and Handles

Use eval() when you want a Dart value. eval() executes JavaScript, converts the result to Dart, and releases the temporary JavaScript handle:

final data = js.eval('({id: 1n, tags: ["a", "b"]})');
// {'id': BigInt.one, 'tags': ['a', 'b']}

Automatic conversion rules:

JavaScript Dart
undefined jsUndefined
null null
boolean bool
integer number int
floating-point number double
bigint BigInt
string String
Array List<dynamic>
plain object Map<String, dynamic>
Date DateTime
Map / Set Map<Object?, Object?> / Set<Object?>
RegExp / Error JsRegExp / JsErrorDetails
ArrayBuffer / TypedArray Uint8List / JsTypedArray
NaN / Infinity / -Infinity Dart special double values

Objects and arrays are converted recursively, so id: 1n becomes Dart BigInt.one, and tags becomes a Dart list. Sparse array holes become jsArrayHole. Passing Dart values into JS supports null, jsUndefined, bool, int, double, String, BigInt, DateTime, Uint8List, JsRegExp, JsErrorDetails, JsTypedArray, Set, List, and Map<String, Object?>.

eval() is for one-shot results and does not preserve JavaScript object identity. Use evalValue() when you need a JsValue handle:

  • Calling JavaScript functions or object methods.
  • Reading or writing object properties or array indexes.
  • Awaiting an existing Promise.
  • Handling circular references, class instances, DOM/host objects, TypedArray/ArrayBuffer, or values that cannot reliably become plain Dart maps/lists.
  • Keeping the same JavaScript object identity across multiple calls.

Use evalValue() when you need to keep a JavaScript object/function handle:

final object = js.evalValue('({count: 2, items: [3, 4]})');
try {
  final count = object.getPropertyValue('count');
  try {
    print(count.toDart()); // 2
  } finally {
    count.dispose();
  }
} finally {
  object.dispose();
}

JsValue.toDart() uses the same conversion rules as eval(). Circular objects cannot be converted automatically:

final circular = js.evalValue('const v = {}; v.self = v; v');
try {
  circular.toDart(); // throws JsException
} finally {
  circular.dispose();
}

Owned JsValue handles must be disposed. Handles received inside registerHandleFunction are borrowed and only valid for the callback duration. Call duplicate() if you need to keep one.

Dart Calls JavaScript

final add = js.evalValue('(function(a, b) { return a + b; })');
try {
  final result = js.callValue(add, [20, 22]);
  try {
    print(result.toDart()); // 42
  } finally {
    result.dispose();
  }
} finally {
  add.dispose();
}

For simple calls:

js.execInitScript('function join(prefix, values) { return prefix + values.join(","); }');
print(js.call('join', ['v:', [1, 2, 3]])); // v:1,2,3

JavaScript Calls Dart

Use registerFunction() to expose a Dart function on the JavaScript global object. JavaScript calls it like a normal function. Arguments are converted to Dart values, and the return value is converted back to JavaScript:

js.registerFunction('dartSum', (args) {
  return args.cast<num>().reduce((a, b) => a + b);
});

print(js.eval('dartSum(4, 5, 6)')); // 15

Callbacks can receive multiple arguments and return convertible values such as Map, List, BigInt, and DateTime:

js.registerFunction('receiveMessage', (args) {
  final name = args[0] as String;
  final payload = args[1] as Map;
  return {
    'ok': true,
    'message': '$name:${payload['count']}',
  };
});

print(js.eval('receiveMessage("counter", {count: 3}).message')); // counter:3

Callbacks may return Future; JavaScript receives a Promise, so JS can use await or .then() directly:

js.registerFunction('loadUser', (args) async {
  return {'id': 1, 'name': 'Ada'};
});

final user = await js.evalAsync('loadUser().then((user) => user.name)');

With JavaScript async/await:

final name = await js.evalAsync('''
  (async () => {
    const user = await loadUser();
    return user.name;
  })()
''');
print(name); // Ada

registerFunction() converts JavaScript objects into Dart snapshots. Use registerHandleFunction() when you need to preserve JavaScript object identity or work with functions, class instances, circular objects, or host objects. It passes arguments to Dart as JsValue handles:

js.registerHandleFunction('readModel', (args) {
  final model = args.first;
  final count = model.getPropertyValue('count');
  try {
    return count.toDart();
  } finally {
    count.dispose();
  }
});

Arguments received by registerHandleFunction() are borrowed handles and are only valid for the callback duration. Call duplicate() if you need to keep one outside the callback, and dispose the owned handle when finished.

Promise

When JavaScript returns a Promise, evalAsync() gives you the resolved Dart value:

final value = await js.evalAsync('Promise.resolve({ok: true})');
print(value); // {'ok': true}

evalAsync() is also the normal way to call async function:

final result = await js.evalAsync('''
  async function compute() {
    const value = await Promise.resolve(21);
    return value * 2;
  }
  compute()
''');
print(result); // 42

You can also await an existing JsValue:

final promise = js.evalValue('Promise.resolve(42)');
try {
  print(await js.awaitValue(promise));
} finally {
  promise.dispose();
}

Dart Future values returned to JavaScript become Promises. This works for both registerFunction() and registerHandleFunction():

js.registerFunction('readConfig', (args) async {
  return {'theme': 'dark'};
});

final theme = await js.evalAsync('''
  readConfig().then((config) => config.theme)
''');
print(theme); // dark

ES Modules

Register modules in memory:

js.registerModules({
  'math': 'export const answer = 42; export function inc(v) { return v + 1; }',
  'consumer': 'import { answer, inc } from "math"; export const result = inc(answer);',
  'pkg/relative': 'import { answer } from "../math"; export const result = answer;',
});

js.registerImportMap({'@math': 'math'});

js.eval(
  'import { result } from "consumer"; globalThis.result = result;',
  filename: 'main',
  module: true,
);

print(js.eval('result')); // 43
print(await js.evalAsync('import("@math").then((m) => m.inc(m.answer))')); // 43

Register a Flutter asset as a module:

await js.registerModuleFromAsset('app/config', 'assets/config.js');

Native platforms use the QuickJS module loader. Web includes JSF's registry loader behind the same Dart API and supports in-memory modules, import maps, relative resolution, module caching, static import, named/default/namespace exports, re-exports, and literal dynamic import("module"). evalAsync(..., module: true) and dynamic import() on Web use the browser's native ES Module/Blob loader, so browser-supported ESM syntax works, including export * from, export { x } from, export * as ns from, and top-level await. The in-memory module loader is intended for application scripts and Flutter asset modules; it does not fetch network module URLs.

Exceptions

JavaScript exceptions are thrown as JsException:

try {
  js.eval('throw new Error("boom")');
} on JsException catch (error) {
  print(error.message);
}

Threading and Lifecycle

  • A JsRuntime owns one QuickJS runtime and one context.
  • Use a runtime from the same Dart isolate that created it.
  • Dispose every runtime with dispose().
  • Dispose owned JsValue handles when you are done.
  • Do not use handles after their runtime is disposed.
  • Disposing a runtime also releases owned JsValue handles still registered under that runtime, but explicit dispose() remains recommended to control memory peaks.

Testing

Integration tests live in example/integration_test:

cd example
flutter drive --driver=integration_test/driver.dart --target=integration_test/js_runtime_test.dart -d macos

The test suite covers primitive conversion, BigInt, object/array conversion, handle calls, Dart callbacks, promise waiting, module loading, exceptions, timeouts, Unicode, typed arrays, circular objects, and multiple runtimes.

카테고리

의존성

의존성 목록 1 개

소스 저장소

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