Skip to content

Commit

Permalink
Merge pull request #67 from pengzhanbo/fix_65
Browse files Browse the repository at this point in the history
  • Loading branch information
pengzhanbo authored Dec 14, 2023
2 parents 20b8d04 + bb38bbf commit 21f2c3a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 11 deletions.
33 changes: 22 additions & 11 deletions src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@ import fg from 'fast-glob'
import isCore from 'is-core-module'
import type { Plugin, ResolvedConfig } from 'vite'
import { createFilter } from '@rollup/pluginutils'
import { name, version } from '../package.json'
import c from 'picocolors'
import { aliasMatches, transformWithEsbuild } from './compiler'
import { viteDefine } from './define'
import type { MockServerPluginOptions, ServerBuildOption } from './types'
import { ensureProxies, lookupFile, normalizePath } from './utils'

declare const __PACKAGE_NAME__: string
declare const __PACKAGE_VERSION__: string

type PluginContext<T = Plugin['buildEnd']> = T extends (
this: infer R,
...args: any[]
Expand Down Expand Up @@ -73,15 +76,21 @@ export async function generateMockServer(
source: generatePackageJson(pkg, mockDeps),
},
]

try {
if (path.isAbsolute(outputDir)) {
for (const { filename } of outputList)
await fsp.rm(filename)

fs.mkdirSync(outputDir, { recursive: true })
for (const { filename, source } of outputList)
for (const { filename } of outputList) {
if (fs.existsSync(filename))
await fsp.rm(filename)
}
config.logger.info(`${c.green('✓')} generate mock server in ${c.cyan(outputDir)}`)
for (const { filename, source } of outputList) {
fs.mkdirSync(path.dirname(filename), { recursive: true })
await fsp.writeFile(filename, source, 'utf-8')
const sourceSize = (source.length / 1024).toFixed(2)
const name = path.relative(outputDir, filename)
const space = name.length < 30 ? ' '.repeat(30 - name.length) : ''
config.logger.info(` ${c.green(name)}${space}${c.bold(c.dim(`${sourceSize} kB`))}`)
}
}
else {
for (const { filename, source } of outputList) {
Expand All @@ -93,12 +102,14 @@ export async function generateMockServer(
}
}
}
catch {}
catch (e) {
console.error(e)
}
}

function getMockDependencies(deps: Metafile['inputs'], alias: ResolvedConfig['resolve']['alias']): string[] {
const list = new Set<string>()
const excludeDeps = [name, 'connect', 'cors']
const excludeDeps = [__PACKAGE_NAME__, 'connect', 'cors']
const isAlias = (p: string) => alias.find(({ find }) => aliasMatches(find, p))
Object.keys(deps).forEach((mPath) => {
const imports = deps[mPath].imports
Expand All @@ -123,7 +134,7 @@ function generatePackageJson(pkg: any, mockDeps: string[]) {
},
dependencies: {
'connect': '^3.7.0',
'vite-plugin-mock-dev-server': `^${version}`,
'vite-plugin-mock-dev-server': `^${__PACKAGE_VERSION__}`,
'cors': '^2.8.5',
} as Record<string, string>,
pnpm: { peerDependencyRules: { ignoreMissing: ['vite'] } },
Expand Down Expand Up @@ -153,7 +164,7 @@ function generatorServerEntryCode(
return `import { createServer } from 'node:http';
import connect from 'connect';
import corsMiddleware from 'cors';
import { baseMiddleware, mockWebSocket, createLogger } from 'vite-plugin-mock-dev-server';
import { baseMiddleware, createLogger, mockWebSocket } from 'vite-plugin-mock-dev-server';
import mockData from './mock-data.js';
const app = connect();
Expand Down
5 changes: 5 additions & 0 deletions tsup.config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { defineConfig } from 'tsup'
import { name, version } from './package.json'

export default defineConfig({
entry: ['src/index.ts'],
Expand All @@ -7,5 +8,9 @@ export default defineConfig({
dts: true,
splitting: false,
clean: true,
define: {
__PACKAGE_NAME__: JSON.stringify(name),
__PACKAGE_VERSION__: JSON.stringify(version),
},
format: ['esm', 'cjs'],
})

0 comments on commit 21f2c3a

Please sign in to comment.