Skip to content
Open
Show file tree
Hide file tree
Changes from 10 commits
Commits
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
8 changes: 4 additions & 4 deletions packages/vite/src/node/__tests__/plugins/import.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,13 @@ describe('runTransform', () => {
test('import all specifier', () => {
expect(runTransformCjsImport('import * as react from "react"', false))
.toMatchInlineSnapshot(`
"import __vite__cjsImport0_react from "./node_modules/.vite/deps/react.js";
const react = ((m, n) => n || !m?.__esModule ? { ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {}, default: m} : m)(__vite__cjsImport0_react, 0)"
`)
"import __vite__cjsImport0_react from "./node_modules/.vite/deps/react.js";
const react = ((m, n) => n || !m?.__esModule ? { ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {}, default: m} : m)(__vite__cjsImport0_react, 0)"
`)
expect(runTransformCjsImport('import * as react from "react"', true))
.toMatchInlineSnapshot(`
"import __vite__cjsImport0_react from "./node_modules/.vite/deps/react.js";
const react = ((m, n) => n || !m?.__esModule ? { ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {}, default: m} : m)(__vite__cjsImport0_react, 1)"
const react = ((m, n) => n || !m?.__esModule ? { ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {}, default: m} : m)(__vite__cjsImport0_react, 1)"
`)
})

Expand Down
43 changes: 42 additions & 1 deletion packages/vite/src/node/optimizer/rolldownDepPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import path from 'node:path'
import type { ImportKind, Plugin, RolldownPlugin } from 'rolldown'
import { prefixRegex } from '@rolldown/pluginutils'
import { JS_TYPES_RE, KNOWN_ASSET_TYPES } from '../constants'
import MagicString from 'magic-string'
import { FS_PREFIX, JS_TYPES_RE, KNOWN_ASSET_TYPES } from '../constants'
import type { PackageCache } from '../packages'
import {
escapeRegex,
Expand All @@ -11,6 +12,7 @@ import {
isExternalUrl,
isNodeBuiltin,
moduleListContains,
normalizePath,
} from '../utils'
import { browserExternalId, optionalPeerDepId } from '../plugins/resolve'
import { isModuleCSSRequest } from '../plugins/css'
Expand Down Expand Up @@ -298,6 +300,45 @@ export function rolldownDepPlugin(
}
},
},
transform: {
filter: { code: /new\s+URL/ },
async handler(code, id) {
if (!id.includes('node_modules')) return null

Comment on lines +306 to +307
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (!id.includes('node_modules')) return null

If the file is bundled by the optimizer, I think we need to resolve the path in new URL.

const s = new MagicString(code)

const workerRE =
/new\s+URL\s*\(\s*['"]([^'"]+)['"]\s*,\s*import\.meta\.url\s*\)/g

let match
while ((match = workerRE.exec(code))) {
const [fullMatch, url] = match
const absolutePath = path.resolve(path.dirname(id), url)
const fsUrl = FS_PREFIX + normalizePath(absolutePath)

// NOTE: add `'' +` to opt-out of Rolldown's static asset analysis.
// This prevents the optimizer from trying to bundle the absolute path
// as a relative asset.
const replacement = `new URL('' + ${JSON.stringify(fsUrl)}, import.meta.url)`

s.overwrite(
match.index,
match.index + fullMatch.length,
replacement,
)

const assetDir = path.dirname(absolutePath)

if (
environment.config.server.fs.allow &&
!environment.config.server.fs.allow.includes(assetDir)
) {
environment.config.server.fs.allow.push(assetDir)
}
Comment on lines +335 to +342
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess this part is not needed because it'll be handled by the other internal plugins.

}
return { code: s.toString(), map: s.generateMap({ hires: true }) }
},
},
},
]
}
Expand Down
9 changes: 9 additions & 0 deletions playground/optimize-deps/__tests__/optimize-deps.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -370,3 +370,12 @@ test.runIf(isServe)(
expect(scanErrors).toHaveLength(0)
},
)

test('should fix standard web worker URLs in optimized dependencies', async () => {
await expect
.poll(() => browserLogs.join('\n'))
.toMatch(/Message from lib: worker-success/)
await expect
.poll(() => browserLogs.join('\n'))
.toMatch(/Message from nested: worker-success/)
})
8 changes: 8 additions & 0 deletions playground/optimize-deps/dep-with-worker-repro/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export function urlImportWorker() {
const worker = new Worker(new URL('./worker.js', import.meta.url), {
type: 'module',
})
return new Promise((res) => {
worker.onmessage = (e) => res(e.data)
})
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export function urlImportWorker() {
// Testing the ../ path traversal
const worker = new Worker(new URL('../worker.js', import.meta.url), {
type: 'module',
})
return new Promise((res) => {
worker.onmessage = (e) => res(e.data)
})
}
9 changes: 9 additions & 0 deletions playground/optimize-deps/dep-with-worker-repro/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "@vitejs/test-dep-with-worker-repro",
"version": "1.0.0",
"type": "module",
"exports": {
".": "./index.js",
"./nested": "./nested/index.js"
}
}
1 change: 1 addition & 0 deletions playground/optimize-deps/dep-with-worker-repro/worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
self.postMessage('worker-success')
7 changes: 7 additions & 0 deletions playground/optimize-deps/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -386,3 +386,10 @@ <h2>Virtual module with .vue extension</h2>
`${VirtualComponent.name === 'VirtualComponent' ? 'ok' : 'ng'}`,
)
</script>
<script type="module">
import * as lib from '@vitejs/test-dep-with-worker-repro'
import * as nested from '@vitejs/test-dep-with-worker-repro/nested'

lib.urlImportWorker().then((m) => console.log('Message from lib:', m))
nested.urlImportWorker().then((m) => console.log('Message from nested:', m))
</script>
1 change: 1 addition & 0 deletions playground/optimize-deps/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"@vitejs/test-dep-non-optimized": "file:./dep-non-optimized",
"@vitejs/test-added-in-entries": "file:./added-in-entries",
"@vitejs/test-dep-cjs-external-package-omit-js-suffix": "file:./dep-cjs-external-package-omit-js-suffix",
"@vitejs/test-dep-with-worker-repro": "file:./dep-with-worker-repro",
"lodash-es": "^4.17.22",
"@vitejs/test-nested-exclude": "file:./nested-exclude",
"phoenix": "^1.8.3",
Expand Down
Loading