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 1 commit
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
29 changes: 29 additions & 0 deletions packages/playground/hmr/__tests__/hmr.spec.ts
Expand Up @@ -160,4 +160,33 @@ 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')

// Modifying a dynamic import that has not been loaded has no effect (doesn't trigger a page reload)
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')
})
}
1 change: 1 addition & 0 deletions packages/playground/hmr/dynamic-import/dep.ts
@@ -0,0 +1 @@
// This file is never loaded
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')
}
21 changes: 13 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,10 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
},

async transform(source, importer, options) {
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 +163,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 +183,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 +203,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 +664,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
6 changes: 6 additions & 0 deletions packages/vite/src/node/server/hmr.ts
Expand Up @@ -225,6 +225,12 @@ function propagateUpdate(
}>,
currentChain: ModuleNode[] = [node]
): boolean /* hasDeadEnd */ {
// 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 === null) {
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 | null = null
brillout marked this conversation as resolved.
Show resolved Hide resolved
brillout marked this conversation as resolved.
Show resolved Hide resolved
transformResult: TransformResult | null = null
ssrTransformResult: TransformResult | null = null
ssrModule: Record<string, any> | null = null
Expand Down