iandis / isolated_worker

An isolated worker for Flutter (Isolate) and Web (Web Worker). Behaves almost the same as the compute function, except it is not a one-off worker.
MIT License
42 stars 11 forks source link

Call external library function #20

Closed alexlozdev closed 1 year ago

alexlozdev commented 1 year ago
final bool loaded = await JsIsolatedWorker().importScripts(['myModule1.js']);
JsIsolatedWorker().run(functionName: 'foo',  arguments: {'src': src, 'toWidth': toWidth,);

// myModule1.js
import pica from "https://cdn.jsdelivr.net/npm/browser-image-compression@2.0.2/dist/browser-image-compression.js";

function resize(param) {
    var src = param["src"];
    var toWidth = param["toWidth"];
    //var callback = param["callback"];

    return pica.resizeBuffer({
        src: src,
        toWidth: toWidth,

    });
}

error : can't find pica library

How can I use function from external libraries?

iandis commented 1 year ago

Hi @alexlozdev,

From what I see, "pica" is actually not defined in "https://cdn.jsdelivr.net/npm/browser-image-compression@2.0.2/dist/browser-image-compression.js". And that library already supports resizing images in web worker, through imageCompression(imageFile, options) with options.useWebWorker is already defaults to true.

But besides that, you can't use import to import on web worker and instead use importScripts([...urls]). Here's a working example:

module1.js:

importScripts([
  'https://cdn.jsdelivr.net/npm/mathjs@11.8.0/lib/browser/math.min.js',
]);

var config = {};
var math = create(all, config);

/**
 *
 * @param {{
 *  num: number,
 *  precision: number,
 * }} param
 *
 * @returns {number}
 */
function mathJs_round(param) {
  return math.round(param.num, param.precision);
}

dartFile.dart:

await JsIsolatedWorker().importScripts(['module1.js']);

double? _mathJsRoundResult;
Future<void> _executeWebModule() async {
  final double result = await JsIsolatedWorker().run(
    functionName: 'mathJs_round',
    arguments: {
      'num': 2.412,
      'precision': 2,
    },
  );
}

Please let me know if this solves the problem.