pengzhanbo / vite-plugin-mock-dev-server

🚀mock-dev-server is injected into the vite development environment to simulate requests and data responses.在vite 开发环境中注入 mock-dev-server, 模拟请求和数据响应
https://vite-plugin-mock-dev-server.netlify.app
MIT License
161 stars 13 forks source link

Invalid define value (must be an entity name or valid JSON syntax): {"BASE_URL":"./","MODE":"production","DEV":false,"PROD":true,"LEGACY":__VITE_IS_LEGACY__} #31

Closed pfdgithub closed 1 year ago

pfdgithub commented 1 year ago

vite@4.3.8@vitejs/plugin-legacy@4.0.3下,启用 options.build 配置后,执行npm run build会报错:

Invalid define value (must be an entity name or valid JSON syntax): {"BASE_URL":"./","MODE":"production","DEV":false,"PROD":true,"LEGACY":__VITE_IS_LEGACY__}

生成了mockServer目录和文件,但mock-data.js文件中是空的。

可能与 babelrollup 版本有关?没往下查,可参考: https://github.com/vitejs/vite/issues/2442 https://github.com/babel/babel/pull/13017 https://github.com/rollup/plugins/pull/838

pengzhanbo commented 1 year ago

经过检查,发现是 @vitejs/plugin-legacy 插件会在 viteConfig.define 配置中插入{ "import.meta.env.LEGACY": '__VITE_IS_LEGACY__' } 。在mock插件中,也会使用 viteConfig.define 用于 插件内部 esbuild 的 define 配置。 但是 在 esbuild 内部 编译时, '__VITE_IS_LEGACY__' 会被替换为一个普通的代码片段 __VITE_IS_LEGACY__,由于代码未定义该变量,导致了编译错误。

pengzhanbo commented 1 year ago

由于 不好判断 viteConfig.define 中的配置,哪些是用户配置的,哪些是插件配置的,以及是否是 注入的待替换字符,目前的解决方式是 过滤掉 import.meta.env.LEGACY

pengzhanbo commented 1 year ago

采用了新的思路, viteConfig.define 配置的字段,如果字符串值 无法被 JSON.parse 解析为 基础类型或 普通对象、普通数组,则将其过滤掉。 从而适配其他可能使用的插件传入的 define 或用户配置的 define 中存在的类似问题。