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: fix HMR propagation when imports not analyzed #7561

Merged
merged 4 commits into from Apr 4, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
34 changes: 34 additions & 0 deletions packages/playground/hmr/__tests__/hmr.spec.ts
Expand Up @@ -160,4 +160,38 @@ if (!isBuild) {
expect(textprev).not.toMatch('direct')
expect(textpost).not.toMatch('direct')
})

test('not loaded dynamic import', async () => {
await page.goto(viteTestUrl + '/dynamic-import/index.html')

let btn = await page.$('button')
expect(await btn.textContent()).toBe('Counter 0')
await btn.click()
expect(await btn.textContent()).toBe('Counter 1')

// Modifying `index.ts` triggers a page reload, as expected
editFile('dynamic-import/index.ts', (code) => code)
await page.waitForNavigation()
btn = await page.$('button')
expect(await btn.textContent()).toBe('Counter 0')

await btn.click()
expect(await btn.textContent()).toBe('Counter 1')

// #7561
// `dep.ts` defines `import.module.hot.accept` and has not been loaded.
// Therefore, modifying it has no effect (doesn't trigger a page reload).
// (Note that, a dynamic import that is never loaded and that does not
// define `accept.module.hot.accept` may wrongfully trigger a full page
// reload, see discussion at #7561.)
editFile('dynamic-import/dep.ts', (code) => code)
try {
await page.waitForNavigation({ timeout: 1000 })
} catch (err) {
const errMsg = 'page.waitForNavigation: Timeout 1000ms exceeded.'
expect(err.message.slice(0, errMsg.length)).toBe(errMsg)
}
btn = await page.$('button')
expect(await btn.textContent()).toBe('Counter 1')
})
}
2 changes: 2 additions & 0 deletions packages/playground/hmr/dynamic-import/dep.ts
@@ -0,0 +1,2 @@
// This file is never loaded
import.meta.hot.accept(() => {})
2 changes: 2 additions & 0 deletions packages/playground/hmr/dynamic-import/index.html
@@ -0,0 +1,2 @@
<button>Counter 0</button>
<script type="module" src="./index.ts"></script>
12 changes: 12 additions & 0 deletions packages/playground/hmr/dynamic-import/index.ts
@@ -0,0 +1,12 @@
const btn = document.querySelector('button')
let count = 0
const update = () => {
btn.textContent = `Counter ${count}`
}
btn.onclick = () => {
count++
update()
}
function neverCalled() {
import('./dep')
}
23 changes: 15 additions & 8 deletions packages/vite/src/node/plugins/importAnalysis.ts
Expand Up @@ -112,7 +112,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
tryIndex: false,
extensions: []
})
let server: ViteDevServer
let server: ViteDevServer | null = null

return {
name: 'vite:import-analysis',
Expand All @@ -122,6 +122,12 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
},

async transform(source, importer, options) {
// In a real app `server` is always defined, but it can be `null` when
// running the test https://github.com/vitejs/vite/blob/a74bd7ba9947be193bccf636b8918bd1f59e89ae/packages/vite/src/node/server/__tests__/pluginContainer.spec.ts
patak-dev marked this conversation as resolved.
Show resolved Hide resolved
if (server === null) {
patak-dev marked this conversation as resolved.
Show resolved Hide resolved
return null
}

const ssr = options?.ssr === true
const prettyImporter = prettifyUrl(importer, root)

Expand Down Expand Up @@ -159,7 +165,13 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
)
}

const { moduleGraph } = server
// since we are already in the transform phase of the importer, it must
// have been loaded so its entry is guaranteed in the module graph.
const importerModule = moduleGraph.getModuleById(importer)!

if (!imports.length) {
importerModule.isSelfAccepting = false
isDebug &&
debug(
`${timeFrom(start)} ${colors.dim(`[no imports] ${prettyImporter}`)}`
Expand All @@ -173,11 +185,6 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
let needQueryInjectHelper = false
let s: MagicString | undefined
const str = () => s || (s = new MagicString(source))
// vite-only server context
const { moduleGraph } = server
// since we are already in the transform phase of the importer, it must
// have been loaded so its entry is guaranteed in the module graph.
const importerModule = moduleGraph.getModuleById(importer)!
const importedUrls = new Set<string>()
const staticImportedUrls = new Set<string>()
const acceptedUrls = new Set<{
Expand All @@ -198,7 +205,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {

let importerFile = importer
if (moduleListContains(config.optimizeDeps?.exclude, url)) {
const optimizedDeps = server._optimizedDeps
const optimizedDeps = server!._optimizedDeps
if (optimizedDeps) {
await optimizedDeps.scanProcessing

Expand Down Expand Up @@ -659,7 +666,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
NULL_BYTE_PLACEHOLDER,
'\0'
)
transformRequest(url, server, { ssr }).catch((e) => {
transformRequest(url, server!, { ssr }).catch((e) => {
if (e?.code === ERR_OUTDATED_OPTIMIZED_DEP) {
// This are expected errors
return
Expand Down
7 changes: 7 additions & 0 deletions packages/vite/src/node/server/hmr.ts
Expand Up @@ -225,6 +225,13 @@ function propagateUpdate(
}>,
currentChain: ModuleNode[] = [node]
): boolean /* hasDeadEnd */ {
// #7561
// if the imports of `node` have not been analyzed, then `node` has not
// been loaded in the browser and we should stop propagation.
if (node.id && node.isSelfAccepting === undefined) {
return false
}

if (node.isSelfAccepting) {
boundaries.add({
boundary: node,
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/server/moduleGraph.ts
Expand Up @@ -27,7 +27,7 @@ export class ModuleNode {
importers = new Set<ModuleNode>()
importedModules = new Set<ModuleNode>()
acceptedHmrDeps = new Set<ModuleNode>()
isSelfAccepting = false
isSelfAccepting?: boolean
transformResult: TransformResult | null = null
ssrTransformResult: TransformResult | null = null
ssrModule: Record<string, any> | null = null
Expand Down