1. 程式人生 > 其它 >使webworker中支援使用import匯入模組——threads.js

使webworker中支援使用import匯入模組——threads.js

threads.js基本使用

使用vue-cli建立一個專案(我這裡vue --version的版本是3.11.0):

vue create hello-world

新增tool.js檔案:

export function getSuffix() {
    return new Date().toDateString()
}

新增webworker.js檔案,import引入tool.js檔案,以驗證webworker中支援import:

import sha256 from "js-sha256"
import { expose } from "threads/worker"
import { getSuffix } 
from './tool' expose({ hashPassword(password, salt) { let suffix = getSuffix(); return sha256(password + salt) + `【當前時間:${suffix}】` } })

新增master.js檔案,

import { spawn, Thread, Worker } from "threads"

export async function getHashPassword() {
    const auth = await spawn(new
Worker("./webworker")) const hashed = await auth.hashPassword("Super secret password", "1234") console.log("Hashed password:", hashed) await Thread.terminate(auth) return hashed; }

注意,Worker從 threads.js 匯入。

其中:

  • spawn()建立一個新的工人
  • expose()宣告您希望您的工作人員公開哪些功能
  • Thread.terminate()一旦你不再需要它就殺死工人

安裝依賴:

npm install threads tiny-worker

使用 webpack 構建

Webpack 配置與threads-plugin一起使用。

它將透明地檢測所有new Worker("./unbundled-path")表示式,捆綁工作程式碼並將new Worker(...)路徑替換為工作包路徑,因此您無需顯式使用worker-loader或定義額外的入口點。

 安裝threads-plugin:

npm install -D threads-plugin

然後將其新增到您的webpack.config.js

const ThreadsPlugin = require('threads-plugin')

  module.exports = {
    // ...
    plugins: [
+     new ThreadsPlugin()
    ]
    // ...
  }

效果:

npm run serve後:

圖中當前時間能正常輸出證明tool.js被正常import了。