fix(browser): skip wrapDynamicImport transform on ssr environment (… · vitest-dev/vitest@d3c964b (original) (raw)

Original file line number Diff line number Diff line change
@@ -344,7 +344,10 @@ export default (parentServer: ParentBrowserProject, base = '/'): Plugin[] => {
344 344 BrowserContext(parentServer),
345 345 dynamicImportPlugin({
346 346 globalThisAccessor: '"__vitest_browser_runner__"',
347 -filter(id) {
347 +filter(id, environment) {
348 +if (environment.name !== 'client') {
349 +return false
350 +}
348 351 if (id.includes(distRoot)) {
349 352 return false
350 353 }
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
1 1 import type { SourceMap } from 'magic-string'
2 -import type { Plugin, Rollup } from 'vite'
2 +import type { Environment, Plugin, Rollup } from 'vite'
3 3 import type { Expression, Positioned } from './esmWalker'
4 4 import MagicString from 'magic-string'
5 5 import { esmWalker } from './esmWalker'
@@ -11,7 +11,7 @@ export interface DynamicImportPluginOptions {
11 11 * @default `"__vitest_mocker__"`
12 12 */
13 13 globalThisAccessor?: string
14 -filter?: (id: string) => boolean
14 +filter?: (id: string, environment: Environment) => boolean
15 15 }
16 16
17 17 export function dynamicImportPlugin(options: DynamicImportPluginOptions = {}): Plugin {
@@ -23,7 +23,7 @@ export function dynamicImportPlugin(options: DynamicImportPluginOptions = {}): P
23 23 if (!regexDynamicImport.test(source)) {
24 24 return
25 25 }
26 -if (options.filter && !options.filter(id)) {
26 +if (options.filter && !options.filter(id, this.environment)) {
27 27 return
28 28 }
29 29 return injectDynamicImport(source, id, this.parse, options)
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
1 +export default async (url: URL) => {
2 +if (url.pathname === '/api/ssr-dep') {
3 +const lib = await import('./ssr-dep')
4 +return lib.default
5 +}
6 +return 'not-found'
7 +}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
1 +export default 'ssr-dep'
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
1 +import { expect, test } from 'vitest'
2 +
3 +test('ssr dynamic import', async () => {
4 +const res = await fetch('/api/ssr-dep')
5 +const text = await res.json()
6 +expect(text).toBe('ssr-dep')
7 +})
Original file line number Diff line number Diff line change
@@ -106,5 +106,26 @@ export default defineConfig({
106 106 await server.ssrLoadModule('/package.json')
107 107 },
108 108 },
109 +{
110 +name: 'my-ssr',
111 +configureServer(server) {
112 +server.middlewares.use(async (req, res, next) => {
113 +const url = new URL(req.url |
114 +if (url.pathname.startsWith('/api/')) {
115 +try {
116 +const mod = await server.ssrLoadModule('./test/server/entry.ts')
117 +const result = await mod.default(url)
118 +res.end(JSON.stringify(result))
119 +return
120 +}
121 +catch (e) {
122 +next(e)
123 +return
124 +}
125 +}
126 +next()
127 +})
128 +},
129 +},
109 130 ],
110 131 })