Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: execute classic worker in dev mode #7099

Merged
merged 22 commits into from Mar 3, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 13 additions & 0 deletions packages/playground/worker/classic-worker.js
@@ -0,0 +1,13 @@
// prettier-ignore
function text(el, text) {
document.querySelector(el).textContent = text
}

const classicWorker = new Worker(
new URL('./newUrl/classic-worker.js', import.meta.url)
)

classicWorker.addEventListener('message', ({ data }) => {
text('.classic-worker', data)
})
classicWorker.postMessage('ping')
19 changes: 13 additions & 6 deletions packages/playground/worker/index.html
Expand Up @@ -20,18 +20,22 @@
<span class="tick-count">0</span>
</div>

<p>new Worker(new Url('path', import.meta.url))</p>
<p>new Worker(new Url('path', import.meta.url), { type: 'module' })</p>
<div class="worker-import-meta-url"></div>

<p>new SharedWorker(new Url('path', import.meta.url))</p>
<p>new SharedWorker(new Url('path', import.meta.url), { type: 'module' })</p>
<div class="shared-worker-import-meta-url"></div>

<p>new Worker(new Url('path', import.meta.url))</p>
poyoho marked this conversation as resolved.
Show resolved Hide resolved
<div class="classic-worker"></div>

<script type="module">
import myWorker from './my-worker?worker'
import InlineWorker from './my-worker?worker&inline'
import mySharedWorker from './my-shared-worker?sharedworker&name=shared'
import TSOutputWorker from './possible-ts-output-worker?worker'
import { mode } from './workerImport'
import './classic-worker'

document.querySelector('.mode-true').textContent = mode

Expand Down Expand Up @@ -78,21 +82,24 @@
function text(el, text) {
document.querySelector(el).textContent = text
}

const workerOptions = { type: 'module' }
// url import worker
const w = new Worker(new URL('./newUrl/url-worker.js', import.meta.url), {
type: 'module'
})
const w = new Worker(
new URL('./newUrl/url-worker.js', import.meta.url),
/* @vite-ignore */ workerOptions
)
w.addEventListener('message', (ev) =>
text(
'.worker-import-meta-url',
'worker import.meta.url' + JSON.stringify(ev.data)
)
)

const genWorkerName = () => 'module'
const w2 = new SharedWorker(
new URL('./newUrl/url-shared-worker.js', import.meta.url),
{
name: genWorkerName(),
type: 'module'
}
)
Expand Down
5 changes: 5 additions & 0 deletions packages/playground/worker/newUrl/classic-worker.js
@@ -0,0 +1,5 @@
importScripts('/classic.js')

self.addEventListener('message', () => {
self.postMessage(self.constant)
})
1 change: 1 addition & 0 deletions packages/playground/worker/public/classic.js
@@ -0,0 +1 @@
self.constant = 'A classic'
75 changes: 71 additions & 4 deletions packages/vite/src/node/plugins/workerImportMetaUrl.ts
Expand Up @@ -13,8 +13,63 @@ import { parseRequest } from '../utils'
import { ENV_PUBLIC_PATH } from '../constants'
import MagicString from 'magic-string'

type WorkerType = 'classic' | 'module' | 'ignore'

const WORKER_FILE_ID = 'worker_url_file'

// find the workerOptions end with `)`
function lexWorkerOptions(code: string, pos: number) {
let pattern = ''
const opStack = []

for (let i = pos; i < code.length; i++) {
const char = code.charAt(i)
if (char === '(') {
opStack.push(char)
} else if (char === ')') {
if (opStack.length) {
opStack.pop()
} else {
break
}
}
pattern += char
}

poyoho marked this conversation as resolved.
Show resolved Hide resolved
pattern = pattern.trim()
if (pattern[0] === ',') {
pattern = pattern.slice(1)
}
return pattern
}

function getWorkerType(code: string, i: number): WorkerType {
const findStart = i
const workerOptionsString = lexWorkerOptions(code, findStart)

const match = /type\s*\:\s*['|"|`]([classic|module]*)['|"|`]/.exec(
workerOptionsString
)
if (match) {
return match[1] as WorkerType
}

if (workerOptionsString.length === 0) {
return 'classic'
}

const hasViteIgnore = /\/\*\s*@vite-ignore\s*\*\//.test(workerOptionsString)
if (!hasViteIgnore) {
throw new Error(
'vite worker options no support dynamic options, ' +
'if you want to ignore this error, ' +
'please use /* @vite-ignore */ in the worker options, ' +
'but the environment variable of vite will be lost.'
)
}
return 'ignore'
}

export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
const isBuild = config.command === 'build'

Expand All @@ -23,9 +78,21 @@ export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin {

async transform(code, id, options) {
const query = parseRequest(id)
if (query && query[WORKER_FILE_ID] != null) {
if (query && query[WORKER_FILE_ID] != null && query['type'] != null) {
const workerType = query['type'] as WorkerType
let injectEnv = ''

if (workerType === 'classic') {
injectEnv = `importScripts('${ENV_PUBLIC_PATH}')\n`
} else if (workerType === 'module') {
injectEnv = `import '${ENV_PUBLIC_PATH}'\n`
} else if (workerType === 'ignore') {
// dynamic worker type we can't know how import the env
injectEnv = ''
}

return {
code: `import '${ENV_PUBLIC_PATH}'\n` + code
code: injectEnv + code
}
}
if (
Expand All @@ -42,7 +109,6 @@ export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
let s: MagicString | null = null
while ((match = importMetaUrlRE.exec(noCommentsCode))) {
const { 0: allExp, 2: exp, 3: rawUrl, index } = match

const urlIndex = allExp.indexOf(exp) + index

if (options?.ssr) {
Expand All @@ -61,7 +127,7 @@ export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
}

s ||= new MagicString(code)

const workerType = getWorkerType(code, index + allExp.length)
const file = path.resolve(path.dirname(id), rawUrl.slice(1, -1))
let url: string
if (isBuild) {
Expand All @@ -80,6 +146,7 @@ export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
} else {
url = await fileToUrl(cleanUrl(file), config, this)
url = injectQuery(url, WORKER_FILE_ID)
url = injectQuery(url, `type=${workerType}`)
}
s.overwrite(urlIndex, urlIndex + exp.length, JSON.stringify(url))
}
Expand Down