Skip to content
Closed
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/config/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@ export default defineConfig(async ({ command, mode }) => {
changeOrigin: true,
configure: (proxy, options) => {
// proxy will be an instance of 'http-proxy'
},
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { run } from '../dist/main.cjs'
import { isBuild } from '../../testUtils'

if (isBuild) {
test('should return result from worker thread', async () => {
const a = await run('ping')
expect(a).toBe('pong')
})
}
31 changes: 31 additions & 0 deletions packages/playground/worker-thread-node/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import MyWorker from './worker?worker'
import InlineWorker from './worker-inline?worker&inline'
import { Worker } from 'worker_threads'

export const run = async (message: string): Promise<string> => {
return new Promise((resolve, reject) => {
const worker = new MyWorker() as Worker
worker.postMessage(message)
worker.on('message', (msg) => {
resolve(msg)
})
})
}

export const inlineWorker = async (message: string): Promise<string> => {
return new Promise((resolve, reject) => {
const worker = new InlineWorker() as Worker
worker.postMessage(message)
worker.on('message', (msg) => {
resolve(msg)
})
})
}

run('ping').then((a) => {
console.log(a)
})

inlineWorker('ping').then((a) => {
console.log(a)
})
10 changes: 10 additions & 0 deletions packages/playground/worker-thread-node/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"name": "worker-thread-node",
"private": true,
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "node scripts/build.js",
"start": "node dist/main.cjs.js"
}
}
3 changes: 3 additions & 0 deletions packages/playground/worker-thread-node/scripts/build.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const vite = require('vite')
const { build } = vite
build({ configFile: 'vite.config.ts' })
18 changes: 18 additions & 0 deletions packages/playground/worker-thread-node/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { defineConfig } from 'vite'
import { builtinModules } from 'module'

export default defineConfig({
build: {
target: 'node16',
outDir: 'dist',
lib: {
entry: 'main.ts',
formats: ['cjs'],
fileName: 'main'
},
rollupOptions: {
external: [...builtinModules]
},
emptyOutDir: true
}
})
5 changes: 5 additions & 0 deletions packages/playground/worker-thread-node/worker-inline.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { parentPort } from 'worker_threads'

parentPort.on('message', () => {
parentPort.postMessage('this is inline node worker')
})
5 changes: 5 additions & 0 deletions packages/playground/worker-thread-node/worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { parentPort } from 'worker_threads'

parentPort.on('message', (message) => {
parentPort.postMessage('pong')
})
6 changes: 4 additions & 2 deletions packages/vite/client.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,15 +164,17 @@ declare module '*.webmanifest' {

// web worker
declare module '*?worker' {
import { Worker as NodeWorker } from 'worker_threads'
const workerConstructor: {
new (): Worker
new (): Worker | NodeWorker
}
export default workerConstructor
}

declare module '*?worker&inline' {
import { Worker as NodeWorker } from 'worker_threads'
const workerConstructor: {
new (): Worker
new (): Worker | NodeWorker
}
export default workerConstructor
}
Expand Down
43 changes: 38 additions & 5 deletions packages/vite/src/node/plugins/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,25 +51,46 @@ export function webWorkerPlugin(config: ResolvedConfig): Plugin {
}

let url: string
const isNode = (config.build.target as string).includes('node')

if (isBuild) {
// bundle the file as entry to support imports
const rollup = require('rollup') as typeof Rollup
const bundle = await rollup.rollup({
input: cleanUrl(id),
...config?.build?.rollupOptions,
plugins: await resolvePlugins({ ...config }, [], [], [])
})

let code: string
try {
const { output } = await bundle.generate({
format: 'iife',
sourcemap: config.build.sourcemap
})
code = output[0].code
if (isNode) {
const { output } = await bundle.generate({
format: 'cjs',
sourcemap: config.build.sourcemap
})
code = output[0].code
} else {
const { output } = await bundle.generate({
format: 'iife',
sourcemap: config.build.sourcemap
})
code = output[0].code
}
} finally {
await bundle.close()
}
const content = Buffer.from(code)
if (query.inline != null) {
if (isNode) {
return `
import { Worker } from "worker_threads" \n
import { join } from "path" \n
export default function WorkerWrapper() {
return new Worker(\'${content.toString().trim()}', { eval: true })
}
`
}
// inline as blob data url
return `const blob = new Blob([atob(\"${content.toString(
'base64'
Expand Down Expand Up @@ -104,6 +125,18 @@ export function webWorkerPlugin(config: ResolvedConfig): Plugin {
query.sharedworker != null ? 'SharedWorker' : 'Worker'
const workerOptions = { type: 'module' }

if (isNode) {
return `
import { Worker } from "worker_threads" \n
import { join } from "path" \n
export default function WorkerWrapper() {
return new Worker(join(__dirname, ${JSON.stringify(
url
)}), ${JSON.stringify(workerOptions, null, 2)})
}
`
}

return `export default function WorkerWrapper() {
return new ${workerConstructor}(${JSON.stringify(
url
Expand Down