Skip to content

Commit

Permalink
refactor: Invalid define value (#31)
Browse files Browse the repository at this point in the history
  • Loading branch information
pengzhanbo committed May 23, 2023
1 parent 97b8294 commit 92d79dd
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 5 deletions.
26 changes: 22 additions & 4 deletions src/define.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
// 在本插件中,简化了处理过程,仅提供 支持在 mock 文件中使用 `define` 和 `env`,并删除了不必要的边界处理。
// 而存在的问题则是,插件并没有对`.env` 文件进行监听,即 `env` 发生变化,不会触发插件的热更新。

import colors from 'picocolors'
import type { ResolvedConfig } from 'vite'
import { log } from './utils'

const metaEnvRe = /import\.meta\.env\.(.+)/

Expand All @@ -24,20 +26,36 @@ export function viteDefine(config: ResolvedConfig) {

const userDefine: Record<string, string> = {}
const userDefineEnv: Record<string, string> = {}
const defineErrorKeys = []
for (const key in config.define) {
// fix: #31 https://github.com/pengzhanbo/vite-plugin-mock-dev-server/issues/31
if (key === 'import.meta.env.LEGACY') continue
const val = config.define[key]
userDefine[key] = typeof val === 'string' ? val : JSON.stringify(val)
if (typeof val === 'string') {
try {
JSON.parse(val)
userDefine[key] = val
} catch {
defineErrorKeys.push(key)
}
} else {
userDefine[key] = JSON.stringify(val)
}

// make sure `import.meta.env` object has user define properties

const match = key.match(metaEnvRe)
if (match) {
if (match && userDefine[key]) {
userDefineEnv[match[1]] = `__vite__define__${userDefine[key]}`
}
}

if (defineErrorKeys.length) {
log.error(
`${colors.yellow('[warn]')} The following keys: ${colors.yellow(
colors.underline(defineErrorKeys.join(', ')),
)} declared in 'define' cannot be parsed as regular code snippets.`,
)
}

const importMetaKeys: Record<string, string> = {}
const importMetaFallbackKeys: Record<string, string> = {}

Expand Down
13 changes: 12 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -451,8 +451,19 @@ export interface MockWebsocketItem extends MockBaseItem {

export interface WebSocketSetupContext {
/**
* When defining WSS, you may perform some automatic or looping tasks.
* However, when hot updating, the plugin will re-execute `setup()`,
* which may result in duplicate registration of listening events and looping tasks
* such as setTimeout. You can use `onCleanup()` to clear these automatic or looping tasks.
*
* 当你在定义 WSS 时,可能会执行一些自动任务或循环任务,
* 但是当热更新时,插件内部会重新执行 setup() ,这可能导致出现
* 但是当热更新时,插件内部会重新执行 setup() ,
* 这可能导致出现 重复注册监听事件 和 循环任务如 `setTimeout` 等。
* 通过 `onCleanup()` 可以来清除这些自动任务或循环任务。
* @example
* ``` ts
* onCleanup(() => clearTimeout(timeId))
* ```
*/
onCleanup: (cleanup: () => void) => void
}
Expand Down

0 comments on commit 92d79dd

Please sign in to comment.