Dify兼容低版本Chrome及iOS APP

1,472 阅读2分钟

Dify兼容低版本Chrome及iOS APP

目前dify使用的版本是1.1.3

1. 存在的问题

  • Dify使用的js语法较新,打包部署时没有向下兼容。 错误表现:Application error: a client-side exception has occurred while loading 10.60.206.9 (see the browser console for more information).

2. 针对Dify的js语法降级

经过测试目前,能够兼容到Chrome浏览器v75版本,safari浏览器v14

Dify默认使用的是pnpm管理依赖,pnpm默认使用硬链接和符号链接管理依赖,但某些项目可能因依赖结构或工具链限制需要更接近 npm/Yarn 的行为,如旧版 Webpack 或 Babel 插件可能依赖 npm 的扁平化 node_modules 结构。

pnpm扁平化安装依赖,web目录下创建.npmrc

node-linker=hoisted

然后再使用pnpm install安装

2.1 为了方便问题排查,关闭代码的压缩和混淆

const nextConfig = {
    webpack: (config, { dev, isServer }) => {
    config.plugins.push(codeInspectorPlugin({ bundler: 'webpack' }))
    config.optimization.minimize = false;
    if (!isServer) {
      config.optimization.minimizer = [];
    }

    return config
  },
}

2.2 修改web/next.config.js文件

将一些依赖包加入编译项中,经过我测试,下面是需要编译的依赖包。

const nextConfig = {
    transpilePackages: ['@tanstack/query-core', 'mermaid', 'marked', 'next/dist/client', 'mdast-util-gfm-autolink-literal', 'ky', 'react-i18next', 'tailwind-merge', 'emoji-mart', '@tanstack/virtual-core', '@reactflow/core', 'hast-util-from-html-isomorphic', 'mime', '@tanstack/react-query', 'hast-util-to-text', 'rehype-katex', 'zundo', '@svgdotjs/svg.js', '@monaco-editor/react', 'micromark-util-decode-numeric-character-reference', 'micromark-util-sanitize-uri'],
}

2.3 替换无法编译的三方包

经过上方编译后,发现在iOS中依然有一个包报错,经确认是该包使用了零宽断言的正则语法,编译时并不能将其降级,因此需要手动兼容。

源码位置是在 dify/web/node_modules/mdast-util-gfm-autolink-literal/lib/index.js

在web目录下创建目录patches,将node_modules目录下的依赖包mdast-util-gfm-autolink-literal拷贝到patches目录下

修改存在兼容的语法规则

搜索搜索函数名transformGfmAutolinkLiterals或者findEmail

因为它是只是一个邮箱验证正则,所以将正则表达式/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu替换为/(?:^|\s|[^\w\s])([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu

function transformGfmAutolinkLiterals(tree) {
  findAndReplace(
    tree,
    [
      [/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi, findUrl],
      // [/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu, findEmail],源码修改前,编译后的零宽断言依旧没转
      [/(?:^|\s|[^\w\s])([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu, findEmail] //修改后
    ],
    {ignore: ['link', 'linkReference']}
  )
}

修改next.config.js配置项,将pathces中的包生效

// next.config.js
module.exports = {
  webpack: (config) => {
    config.resolve.alias['mdast-util-gfm-autolink-literal'] = 
      require.resolve('./patches/mdast-util-gfm-autolink-literal');
    return config;
  }
}

目前这套写法在1.4.1上有效,将来如果升级版本了,可以根据控制台哪个依赖包报错了,优先放在transpilePackages中进行编译,编译后依然报错的话,就拷贝到pathces目录,自己手动修改,修改后在webpack配置项中为该依赖包设置别名,并修改引用地址即可。