在Typescript / Webpack项目中使用Web Worker的问题

时间:2019-12-30 18:56:32

标签: reactjs typescript webpack

最接近我的东西就是这个错误。

  

未捕获的TypeError:无法构造'Worker':> DedicatedWorker尚不支持模块脚本。您可以使用“ --enable-experimental-web-platform->功能”标志来试用该功能

这是项目的设置方式。

tsconfig.json

{
  "compilerOptions": {
    "jsx": "react",
    "lib": ["es2017", "dom"],
    "downlevelIteration": true,
    "strict": true,
    "skipLibCheck": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "outDir": "./lib",
    "target": "es5"
  }
}

webpack.config.js

...config,
  entry: {
    main: './src/index.tsx',
    notSupported: './src/notSupported.tsx',
  },
  output: {
    path: path.join(__dirname, 'dist', 'app'),
    filename: '[name].[hash].js',
  },
rules: [
      {
        test: /\.worker\.[tj]s$/,
        loader: 'worker-loader',
      },
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        loader: 'awesome-typescript-loader',
      },
    ...rules,
],

src / worker.d.ts

declare module 'worker-loader!*' {
  class WebpackWorker extends Worker {
    constructor();
  }

  export default WebpackWorker;
}

src / test.worker.ts

console.log('hello from a webworker');

addEventListener('message', (message: any) => {
  console.log('in webworker', message);
  postMessage('this is the response ' + message, 'targetOrigin');
});

src / index.tsx

const worker = new Worker('worker-loader!./test.worker', {type: 'module'});
worker.addEventListener('message', (data: any) => {
  console.log('index worker: ', data);
});

...
<button onClick={() => worker.postMessage('Clicking Btn')}>Test</button>

0 个答案:

没有答案