简体   繁体   中英

Uncaught TypeError: worker.postMessage is not a function (js)

I'm trying to implement a function using a worker. The source code is as follows, but I received an error message saying, "Uncaught Type Error: worker.postMessage is not a function." What should I do?

I am working on react.

someModule.js

import WorkerScript from './process.worker.js';

var SomeModule = (function() {
  if (window.Worker) {
    let worker = new WorkerScript();
    worker.onmessage = (event) => {
      console.log(event.data);
    }

    const someFunction = function(blob, decomposition = false) {
      worker.postMessage({ init : true }); //The part where an error occurs.
      ...
    }
  }
})

process.worker.js

export default class WorkerScript {
  constructor() {
    console.log("Worker Enabled.");
    ...

    if ("function" === typeof importScripts) {
      importScripts("Mp3LameEncoder.min.js");
    }

    ...

    onmessage = (event) => {
      if (event.data.init) {
        index = 0;
      } else {
        Promise.resolve(event.data).then(convert());
      }
    };

    // Buffer needs two channels
    function convert() {
      index++;
      return (buffer) => {
        ...
        postMessage({
          index: buffer.step,
          ...
        });
      };
    }
  }
}

The original codes of the above two can be found in the link below. https://github.com/yoannck/WebM-MP3

config-overrides.js (at root)

const lodashCloneDeep = require('lodash/cloneDeep');

module.exports = function override(config, env) {
    // Add worker-loader by hijacking configuration for regular .js files.

    const workerExtension = /\.worker\.js$/;

    ...

    return config;
};

The full source code of 'config-overrides.js' can be seen here. https://github.com/facebook/create-react-app/issues/1277#issuecomment-313950613

If I print the worker into the console, it's as follows. ibb.co/JKQV8rq

I do not know React but someone from another forum said that you have to manually add the plugin. I don't understand it but it was something like this, and it was marked as working:

const WorkerPlugin = require('worker-plugin');
plugins: [
new WorkerPlugin(),
...

I hope this points you at least to the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM