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

refactor: let the mean of publicPath and filePath more clear and … #266

Merged
merged 1 commit into from
May 26, 2020
Merged
Show file tree
Hide file tree
Changes from all 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: 6 additions & 2 deletions src/node/server/serverPluginHmr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,12 @@ import { cssPreprocessLangRE } from '../utils/cssUtils'
export const debugHmr = require('debug')('vite:hmr')

export type HMRWatcher = FSWatcher & {
handleVueReload: (file: string, timestamp?: number, content?: string) => void
handleJSReload: (file: string, timestamp?: number) => void
handleVueReload: (
filePath: string,
timestamp?: number,
content?: string
) => void
handleJSReload: (filePath: string, timestamp?: number) => void
send: (payload: HMRPayload) => void
}

Expand Down
88 changes: 45 additions & 43 deletions src/node/server/serverPluginVue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,10 @@ export const vuePlugin: ServerPlugin = ({

const query = ctx.query
const publicPath = ctx.path
let filename = resolver.requestToFile(publicPath)
let filePath = resolver.requestToFile(publicPath)

// upstream plugins could've already read the file
const descriptor = await parseSFC(root, filename, ctx.body)
const descriptor = await parseSFC(root, filePath, ctx.body)
if (!descriptor) {
debug(`${ctx.url} - 404`)
ctx.status = 404
Expand All @@ -84,23 +84,23 @@ export const vuePlugin: ServerPlugin = ({

if (!query.type) {
if (descriptor.script && descriptor.script.src) {
filename = await resolveSrcImport(descriptor.script, ctx, resolver)
filePath = await resolveSrcImport(descriptor.script, ctx, resolver)
}
ctx.type = 'js'
ctx.body = await compileSFCMain(descriptor, filename, publicPath)
ctx.body = await compileSFCMain(descriptor, filePath, publicPath)
return etagCacheCheck(ctx)
}

if (query.type === 'template') {
const templateBlock = descriptor.template!
if (templateBlock.src) {
filename = await resolveSrcImport(templateBlock, ctx, resolver)
filePath = await resolveSrcImport(templateBlock, ctx, resolver)
}
ctx.type = 'js'
ctx.body = compileSFCTemplate(
root,
templateBlock,
filename,
filePath,
publicPath,
descriptor.styles.some((s) => s.scoped),
config.vueCompilerOptions
Expand All @@ -112,14 +112,14 @@ export const vuePlugin: ServerPlugin = ({
const index = Number(query.index)
const styleBlock = descriptor.styles[index]
if (styleBlock.src) {
filename = await resolveSrcImport(styleBlock, ctx, resolver)
filePath = await resolveSrcImport(styleBlock, ctx, resolver)
}
const id = hash_sum(publicPath)
const result = await compileSFCStyle(
root,
styleBlock,
index,
filename,
filePath,
publicPath
)
ctx.type = 'js'
Expand All @@ -131,18 +131,18 @@ export const vuePlugin: ServerPlugin = ({
})

const handleVueReload = (watcher.handleVueReload = async (
file: string,
filePath: string,
timestamp: number = Date.now(),
content?: string
) => {
const publicPath = resolver.fileToRequest(file)
const cacheEntry = vueCache.get(file)
const publicPath = resolver.fileToRequest(filePath)
const cacheEntry = vueCache.get(filePath)
const { send } = watcher

debugHmr(`busting Vue cache for ${file}`)
vueCache.del(file)
debugHmr(`busting Vue cache for ${filePath}`)
vueCache.del(filePath)

const descriptor = await parseSFC(root, file, content)
const descriptor = await parseSFC(root, filePath, content)
if (!descriptor) {
// read failed
return
Expand All @@ -151,7 +151,7 @@ export const vuePlugin: ServerPlugin = ({
const prevDescriptor = cacheEntry && cacheEntry.descriptor
if (!prevDescriptor) {
// the file has never been accessed yet
debugHmr(`no existing descriptor found for ${file}`)
debugHmr(`no existing descriptor found for ${filePath}`)
return
}

Expand All @@ -166,7 +166,7 @@ export const vuePlugin: ServerPlugin = ({
})
console.log(
chalk.green(`[vite:hmr] `) +
`${path.relative(root, file)} updated. (reload)`
`${path.relative(root, filePath)} updated. (reload)`
)
}

Expand Down Expand Up @@ -239,7 +239,9 @@ export const vuePlugin: ServerPlugin = ({
if (updateType.length) {
console.log(
chalk.green(`[vite:hmr] `) +
`${path.relative(root, file)} updated. (${updateType.join(' & ')})`
`${path.relative(root, filePath)} updated. (${updateType.join(
' & '
)})`
)
}
})
Expand Down Expand Up @@ -271,31 +273,31 @@ async function resolveSrcImport(
) {
const importer = ctx.path
const importee = resolveRelativeRequest(importer, block.src!).url
const filename = resolver.requestToFile(importee)
await cachedRead(ctx, filename)
const filePath = resolver.requestToFile(importee)
await cachedRead(ctx, filePath)
block.content = ctx.body

// register HMR import relationship
debugHmr(` ${importer} imports ${importee}`)
ensureMapEntry(importerMap, importee).add(ctx.path)
srcImportMap.set(filename, ctx.url)
return filename
srcImportMap.set(filePath, ctx.url)
return filePath
}

export async function parseSFC(
root: string,
filename: string,
filePath: string,
content?: string | Buffer
): Promise<SFCDescriptor | undefined> {
let cached = vueCache.get(filename)
let cached = vueCache.get(filePath)
if (cached && cached.descriptor) {
debug(`${filename} parse cache hit`)
debug(`${filePath} parse cache hit`)
return cached.descriptor
}

if (!content) {
try {
content = await cachedRead(null, filename)
content = await cachedRead(null, filePath)
} catch (e) {
return
}
Expand All @@ -308,7 +310,7 @@ export async function parseSFC(
const start = Date.now()
const { parse, generateCodeFrame } = resolveCompiler(root)
const { descriptor, errors } = parse(content, {
filename,
filename: filePath,
sourceMap: true
})

Expand All @@ -317,7 +319,7 @@ export async function parseSFC(
errors.forEach((e) => {
console.error(
chalk.underline(
`${filename}:${e.loc!.start.line}:${e.loc!.start.column}`
`${filePath}:${e.loc!.start.line}:${e.loc!.start.column}`
)
)
console.error(chalk.yellow(e.message))
Expand All @@ -333,8 +335,8 @@ export async function parseSFC(

cached = cached || { styles: [] }
cached.descriptor = descriptor
vueCache.set(filename, cached)
debug(`${filename} parsed in ${Date.now() - start}ms.`)
vueCache.set(filePath, cached)
debug(`${filePath} parsed in ${Date.now() - start}ms.`)
return descriptor
}

Expand Down Expand Up @@ -411,12 +413,12 @@ async function compileSFCMain(
function compileSFCTemplate(
root: string,
template: SFCTemplateBlock,
filename: string,
filePath: string,
publicPath: string,
scoped: boolean,
userOptions: CompilerOptions | undefined
): string {
let cached = vueCache.get(filename)
let cached = vueCache.get(filePath)
if (cached && cached.template) {
debug(`${publicPath} template cache hit`)
return cached.template
Expand All @@ -426,7 +428,7 @@ function compileSFCTemplate(
const { compileTemplate, generateCodeFrame } = resolveCompiler(root)
const { code, map, errors } = compileTemplate({
source: template.content,
filename,
filename: filePath,
inMap: template.map,
transformAssetUrls: {
base: path.posix.dirname(publicPath)
Expand All @@ -448,7 +450,7 @@ function compileSFCTemplate(
} else {
console.error(
chalk.underline(
`${filename}:${e.loc!.start.line}:${e.loc!.start.column}`
`${filePath}:${e.loc!.start.line}:${e.loc!.start.column}`
)
)
console.error(chalk.yellow(e.message))
Expand All @@ -464,7 +466,7 @@ function compileSFCTemplate(
const finalCode = code + genSourceMapString(map)
cached = cached || { styles: [] }
cached.template = finalCode
vueCache.set(filename, cached)
vueCache.set(filePath, cached)

debug(`${publicPath} template compiled in ${Date.now() - start}ms.`)
return finalCode
Expand All @@ -474,10 +476,10 @@ async function compileSFCStyle(
root: string,
style: SFCStyleBlock,
index: number,
filename: string,
filePath: string,
publicPath: string
): Promise<SFCStyleCompileResults> {
let cached = vueCache.get(filename)
let cached = vueCache.get(filePath)
const cachedEntry = cached && cached.styles && cached.styles[index]
if (cachedEntry) {
debug(`${publicPath} style cache hit`)
Expand All @@ -490,7 +492,7 @@ async function compileSFCStyle(

const result = (await compileCss(root, publicPath, {
source: style.content,
filename,
filename: filePath,
id: ``, // will be computed in compileCss
scoped: style.scoped != null,
modules: style.module != null,
Expand All @@ -506,17 +508,17 @@ async function compileSFCStyle(
const lineOffset = style.loc.start.line - 1
if (e.line && e.column) {
console.log(
chalk.underline(`${filename}:${e.line + lineOffset}:${e.column}`)
chalk.underline(`${filePath}:${e.line + lineOffset}:${e.column}`)
)
} else {
console.log(chalk.underline(filename))
console.log(chalk.underline(filePath))
}
const filenameRE = new RegExp(
const filePathRE = new RegExp(
'.*' +
path.basename(filename).replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&') +
path.basename(filePath).replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&') +
'(:\\d+:\\d+:\\s*)?'
)
const cleanMsg = e.message.replace(filenameRE, '')
const cleanMsg = e.message.replace(filePathRE, '')
console.error(chalk.yellow(cleanMsg))
if (e.line && e.column && cleanMsg.split(/\n/g).length === 1) {
const original = style.map!.sourcesContent![0]
Expand All @@ -538,7 +540,7 @@ async function compileSFCStyle(

cached = cached || { styles: [] }
cached.styles[index] = result
vueCache.set(filename, cached)
vueCache.set(filePath, cached)

debug(`${publicPath} style compiled in ${Date.now() - start}ms`)
return result
Expand Down