Skip to content

Commit

Permalink
feat(worker): allow new URL to resolve workers from package aliases
Browse files Browse the repository at this point in the history
  • Loading branch information
kherock committed Apr 22, 2022
1 parent 099f2b8 commit f29bb97
Show file tree
Hide file tree
Showing 7 changed files with 54 additions and 15 deletions.
4 changes: 4 additions & 0 deletions packages/playground/worker/__tests__/es/es-worker.spec.ts
Expand Up @@ -82,6 +82,10 @@ if (isBuild) {
}

test('module worker', async () => {
expect(await page.textContent('.worker-import-meta-url')).toMatch('A string')
expect(await page.textContent('.worker-import-meta-url-resolve')).toMatch(
'A string'
)
expect(await page.textContent('.shared-worker-import-meta-url')).toMatch(
'A string'
)
Expand Down
4 changes: 4 additions & 0 deletions packages/playground/worker/__tests__/iife/worker.spec.ts
Expand Up @@ -85,6 +85,10 @@ if (isBuild) {
}

test('module worker', async () => {
expect(await page.textContent('.worker-import-meta-url')).toMatch('A string')
expect(await page.textContent('.worker-import-meta-url-resolve')).toMatch(
'A string'
)
expect(await page.textContent('.shared-worker-import-meta-url')).toMatch(
'A string'
)
Expand Down
6 changes: 6 additions & 0 deletions packages/playground/worker/index.html
Expand Up @@ -32,6 +32,12 @@ <h2 class="format-iife">format iife:</h2>
</p>
<code class="worker-import-meta-url"></code>

<p>
new Worker(new URL('@/url-worker', import.meta.url), { type: 'module' })
<span class="classname">.worker-import-meta-url-resolve</span>
</p>
<code class="worker-import-meta-url-resolve"></code>

<p>
new SharedWorker(new URL('./url-shared-worker.js', import.meta.url), { type:
'module' })
Expand Down
6 changes: 6 additions & 0 deletions packages/playground/worker/vite.config.js
@@ -1,8 +1,14 @@
const vueJsx = require('@vitejs/plugin-vue-jsx')
const path = require('path')
const vite = require('vite')

module.exports = vite.defineConfig({
base: '/iife/',
resolve: {
alias: {
'@': __dirname
}
},
worker: {
format: 'iife',
plugins: [vueJsx()]
Expand Down
9 changes: 9 additions & 0 deletions packages/playground/worker/worker/main-module.js
Expand Up @@ -70,6 +70,15 @@ w.addEventListener('message', (ev) =>
text('.worker-import-meta-url', JSON.stringify(ev.data))
)

// url import worker with alias path
const wResolve = new Worker(
new URL('@/url-worker', import.meta.url),
/* @vite-ignore */ workerOptions
)
wResolve.addEventListener('message', (ev) =>
text('.worker-import-meta-url-resolve', JSON.stringify(ev.data))
)

const genWorkerName = () => 'module'
const w2 = new SharedWorker(
new URL('../url-shared-worker.js', import.meta.url),
Expand Down
7 changes: 4 additions & 3 deletions packages/vite/src/node/plugins/worker.ts
Expand Up @@ -278,10 +278,11 @@ export function webWorkerPlugin(config: ResolvedConfig): Plugin {
}
},

renderChunk(code) {
if (isWorker && code.includes('import.meta.url')) {
return code.replace('import.meta.url', 'self.location.href')
resolveImportMeta(property) {
if (isWorker && property === 'url') {
return 'self.location.href'
}
return null
}
}
}
33 changes: 21 additions & 12 deletions packages/vite/src/node/plugins/workerImportMetaUrl.ts
Expand Up @@ -2,13 +2,12 @@ import JSON5 from 'json5'
import type { ResolvedConfig } from '../config'
import type { Plugin } from '../plugin'
import { fileToUrl } from './asset'
import { cleanUrl, injectQuery } from '../utils'
import path from 'path'
import { injectQuery } from '../utils'
import { workerFileToUrl } from './worker'
import { parseRequest } from '../utils'
import { ENV_ENTRY, ENV_PUBLIC_PATH } from '../constants'
import MagicString from 'magic-string'
import type { ViteDevServer } from '..'
import type { ResolveFn, ViteDevServer } from '..'
import type { RollupError } from 'rollup'
import { emptyString } from '../cleanString'

Expand Down Expand Up @@ -70,6 +69,7 @@ function getWorkerType(raw: string, clean: string, i: number): WorkerType {
export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
const isBuild = config.command === 'build'
let server: ViteDevServer
let workerResolver: ResolveFn

return {
name: 'vite:worker-import-meta-url',
Expand Down Expand Up @@ -144,18 +144,27 @@ export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
cleanString,
index + allExp.length
)
const file = path.resolve(path.dirname(id), rawUrl.slice(1, -1))
let url: string
const url = rawUrl.slice(1, -1)
workerResolver ??= config.createResolver({
tryIndex: false,
preferRelative: true
})
const file = (await workerResolver(url, id)) ?? url

let builtUrl: string
if (isBuild) {
url = await workerFileToUrl(this, config, file, query)
builtUrl = await workerFileToUrl(this, config, file, query)
} else {
url = await fileToUrl(cleanUrl(file), config, this)
url = injectQuery(url, WORKER_FILE_ID)
url = injectQuery(url, `type=${workerType}`)
builtUrl = await fileToUrl(file, config, this)
builtUrl = injectQuery(builtUrl, WORKER_FILE_ID)
builtUrl = injectQuery(builtUrl, `type=${workerType}`)
}
s.overwrite(urlIndex, urlIndex + exp.length, JSON.stringify(url), {
contentOnly: true
})
s.overwrite(
urlIndex,
urlIndex + exp.length,
`new URL(${JSON.stringify(builtUrl)}, self.location)`,
{ contentOnly: true }
)
}

if (s) {
Expand Down

0 comments on commit f29bb97

Please sign in to comment.