Skip to content

Commit

Permalink
fix(scan): do not match 'export default' in comments (#4602)
Browse files Browse the repository at this point in the history
  • Loading branch information
ygj6 committed Aug 16, 2021
1 parent b97afa7 commit 8b85f5f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
20 changes: 19 additions & 1 deletion packages/vite/src/node/__tests__/scan.spec.ts
@@ -1,4 +1,10 @@
import { scriptRE, commentRE, importsRE } from '../optimizer/scan'
import {
scriptRE,
commentRE,
importsRE,
multilineCommentsRE,
singlelineCommentsRE
} from '../optimizer/scan'

describe('optimizer-scan:script-test', () => {
const scriptContent = `import { defineComponent } from 'vue'
Expand Down Expand Up @@ -102,4 +108,16 @@ describe('optimizer-scan:script-test', () => {
expect(importsRE.test(str)).toBe(false)
})
})

test('script comments test', () => {
multilineCommentsRE.lastIndex = 0
let ret = `/*
export default { }
*/`.replace(multilineCommentsRE, '')
expect(ret).not.toContain('export default')

singlelineCommentsRE.lastIndex = 0
ret = `//export default { }`.replace(singlelineCommentsRE, '')
expect(ret).not.toContain('export default')
})
})
13 changes: 8 additions & 5 deletions packages/vite/src/node/optimizer/scan.ts
Expand Up @@ -40,7 +40,8 @@ const htmlTypesRE = /\.(html|vue|svelte)$/
export const importsRE =
/(?<!\/\/.*)(?<=^|;|\*\/)\s*import(?!\s+type)(?:[\w*{}\n\r\t, ]+from\s*)?\s*("[^"]+"|'[^']+')\s*(?=$|;|\/\/|\/\*)/gm

const multilineCommentsRE = /\/\*(.|[\r\n])*?\*\//gm
export const multilineCommentsRE = /\/\*(.|[\r\n])*?\*\//gm
export const singlelineCommentsRE = /\/\/.*/g

export async function scanImports(config: ResolvedConfig): Promise<{
deps: Record<string, string>
Expand Down Expand Up @@ -235,6 +236,10 @@ function esbuildScanPlugin(
js += content + '\n'
}
}
// empty singleline & multiline comments to avoid matching comments
const code = js
.replace(multilineCommentsRE, '/* */')
.replace(singlelineCommentsRE, '')

if (
loader.startsWith('ts') &&
Expand All @@ -247,8 +252,6 @@ function esbuildScanPlugin(
// the solution is to add `import 'x'` for every source to force
// esbuild to keep crawling due to potential side effects.
let m
// empty multiline comments to avoid matching commented out imports
const code = js.replace(multilineCommentsRE, '/* */')
while ((m = importsRE.exec(code)) != null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === importsRE.lastIndex) {
Expand All @@ -258,11 +261,11 @@ function esbuildScanPlugin(
}
}

if (!js.includes(`export default`)) {
if (!code.includes(`export default`)) {
js += `\nexport default {}`
}

if (js.includes('import.meta.glob')) {
if (code.includes('import.meta.glob')) {
return {
// transformGlob already transforms to js
loader: 'js',
Expand Down

0 comments on commit 8b85f5f

Please sign in to comment.