vite.config.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import { defineConfig, type Plugin } from 'vite';
  2. import uni from '@dcloudio/vite-plugin-uni';
  3. /**
  4. * sm-crypto-v2 两处 App 端适配:
  5. * 1) 内含 `await import("crypto")`(Node CSPRNG 兜底分支),会使 Rollup 产出第二个 chunk,
  6. * 与 App 端 app-service 的 iife 单文件格式冲突,构建期改写为同步引用。
  7. * 2) 其顶层 `initRNGPool()` 在模块求值时执行,而 uni-app 虚拟入口会让 sm-crypto 先于
  8. * src/signalr/polyfill.ts 执行(实测 bundle 中 sm-crypto 在 ~47k、polyfill 在 ~409k),
  9. * 导致初始化时 globalThis.crypto 尚不存在、随机数池永久为空(randomBytes 抛
  10. * "random number pool is not ready")。给 randomBytes 加惰性重检,调用时再认一次 crypto。
  11. */
  12. function stripSmCryptoDynamicImport(): Plugin {
  13. return {
  14. name: 'strip-sm-crypto-dynamic-import',
  15. enforce: 'pre',
  16. transform(code, id) {
  17. if (!id.includes('sm-crypto-v2')) return null;
  18. let patched = code.replace(
  19. /const crypto = await import\(\s*\/\* webpackIgnore: true \*\/\s*"crypto"\s*\);/,
  20. 'const crypto = { webcrypto: globalThis.crypto };'
  21. );
  22. patched = patched.replace(
  23. /function randomBytes\(length = 0\) \{\s*const array = new Uint8Array\(length\);\s*if \(_syncCrypto\) \{/,
  24. 'function randomBytes(length = 0) {\n const array = new Uint8Array(length);\n if (!_syncCrypto && "crypto" in globalThis) _syncCrypto = globalThis.crypto;\n if (_syncCrypto) {'
  25. );
  26. return patched === code ? null : { code: patched, map: null };
  27. },
  28. };
  29. }
  30. export default defineConfig({
  31. plugins: [stripSmCryptoDynamicImport(), uni()],
  32. server: {
  33. host: '0.0.0.0',
  34. },
  35. });