基于 Web Worker 实现的后台计算方法,提供了 Vite 钩子,可让 Vite 项目中的 JS 模块多线程运行
npm install web-worker-enhancejs
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import { viteConvertWorker } from 'web-worker-enhance/hooks/vite-convert-worker'
const workerPath = fileURLToPath(new URL('./src/utils', import.meta.url))
export default defineConfig({
plugins: [
vue(),
vueDevTools(),
viteConvertWorker(workerPath)],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
}
})
`
#### 内置模块
- hashCode 计算文件哈希码
1. hashCode(file,onProgress)
2. toStreamChunk(file, fn)
`js
import { Thread } from 'web-worker-enhance'
await Thread.run('hashCode', 'hashCode', [file,progress=>{}], {
isNewThread: false,
timeout: -1,
isMainThread: false
})
await Thread.runAs('hashCode', 'hashCode', file,progress=>{})
await Thread.runAsNew('hashCode', 'hashCode', file,progress=>{})
``