Skip to content
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
1 change: 1 addition & 0 deletions example/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export default defineConfig(({ mode }) => ({
prefix: '^/api-dev/',
wsPrefix: ['/socket.io'],
log: 'debug',
reload: true,
formidableOptions: {
// 配置上传资源存放目录
uploadDir: path.join(process.cwd(), '/uploads'),
Expand Down
27 changes: 15 additions & 12 deletions vite-plugin-mock-dev-server/src/compiler/loadFromCode.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { createHash } from 'node:crypto'
import fs, { promises as fsp } from 'node:fs'
import path from 'node:path'
import { pathToFileURL } from 'node:url'
import { attempt, attemptAsync } from '@pengzhanbo/utils'

interface LoadFromCodeOptions {
filepath: string
Expand All @@ -17,17 +19,18 @@ export async function loadFromCode<T = any>({
}: LoadFromCodeOptions): Promise<T | { [key: string]: T }> {
filepath = path.resolve(cwd, filepath)
const ext = isESM ? '.mjs' : '.cjs'
const filepathTmp = `${filepath}.timestamp-${Date.now()}${ext}`
const file = pathToFileURL(filepathTmp).toString()
const filepathTmp = `${filepath}.${getHash(code)}${ext}`
await fsp.writeFile(filepathTmp, code, 'utf8')
try {
const mod = await import(file)
return mod.default || mod
}
finally {
try {
fs.unlinkSync(filepathTmp)
}
catch {}
}
const [, mod] = await attemptAsync(importDefault, String(pathToFileURL(filepathTmp)))
attempt(fs.unlinkSync, filepathTmp)
return mod
}

async function importDefault(filepath: string): Promise<any> {
const mod = await import(filepath)
return mod.default || mod
}

function getHash(str: string): string {
return createHash('md5').update(str).digest('hex')
}
2 changes: 1 addition & 1 deletion vite-plugin-mock-dev-server/src/compiler/rolldown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export async function transformWithRolldown(
})
return {
code: result.output[0].code,
deps: result.output[0].imports.map(normalizePath),
deps: result.output[0].moduleIds.filter(id => !id.endsWith(filename)).map(id => normalizePath(path.relative(cwd, id))),
}
}
catch (e) {
Expand Down
4 changes: 2 additions & 2 deletions vite-plugin-mock-dev-server/src/mockHttp/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ export function createMockMiddleware(

if (error) {
logger.error(
`${ansis.red(`mock error at ${pathname}`)}\n${error}\n at body (${ansis.underline(filepath)})`,
`${ansis.red(`mock error at ${pathname}`)}\n ${error}\n at body (${ansis.underline.gray(filepath)})`,
logLevel,
)
provideResponseStatus(response, 500)
Expand All @@ -214,7 +214,7 @@ export function createMockMiddleware(
logger.error(
`${ansis.red(
`mock error at ${pathname}`,
)}\n${error}\n at response (${ansis.underline(filepath)})`,
)}\n ${error}\n at response (${ansis.underline.gray(filepath)})`,
logLevel,
)
provideResponseStatus(response, 500)
Expand Down
Loading