You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node/React项目使用any-text报require函数无法静态提取错误

问题根源

你遇到的警告本质是两个问题叠加导致的:

  1. any-text 是面向Node.js服务端设计的依赖,内部依赖fs等Node原生API,本身不支持在浏览器环境的React前端项目中直接运行,你安装的fs@0.0.1-security是空占位包,实际运行相关功能时仍然会报错,警告只是前置的编译提示
  2. any-text依赖的pdf-parse包内置了多个版本的旧版pdf.js,其中大量使用动态require语法,webpack(react-scripts底层打包工具)无法静态分析依赖,因此抛出编译警告

最优解决方案(推荐)

放弃在前端直接使用any-text,利用你项目中已安装的依赖分别实现多类型文件的文本提取,完全兼容浏览器环境:

  • TXT文件:直接使用浏览器原生FileReader API读取上传的File对象即可
  • DOCX文件:使用已安装的mammoth,调用浏览器端兼容的API实现文本提取:
const extractDocxText = async (file) => {
  const arrayBuffer = await file.arrayBuffer()
  const result = await mammoth.extractRawText({ arrayBuffer })
  return result.value
}
  • PDF文件:使用已安装的react-pdf内置的pdfjs能力实现文本提取,无需依赖pdf-parse:
import * as pdfjsLib from 'react-pdf/dist/esm/pdfjs-lib'
// 配置pdfjs worker地址
pdfjsLib.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjsLib.version}/pdf.worker.min.js`

const extractPdfText = async (file) => {
  const arrayBuffer = await file.arrayBuffer()
  const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise
  let fullText = ''
  for (let i = 1; i <= pdf.numPages; i++) {
    const page = await pdf.getPage(i)
    const textContent = await page.getTextContent()
    fullText += textContent.items.map(item => item.str).join(' ') + '\n'
  }
  return fullText
}

完成后卸载any-text即可彻底消除警告,功能也能正常在前端运行。

临时消警告方案(不推荐,仅后端项目或确认功能可运行时使用)

如果你确定要保留any-text(比如相关逻辑是放在项目的Node后端部分),可以通过修改webpack配置屏蔽警告:

  1. 安装配置依赖
npm install react-app-rewired customize-cra --save-dev
  1. 修改package.json中的scripts字段,将所有react-scripts替换为react-app-rewired:
"scripts": {
  "start": "react-app-rewired start",
  "build": "react-app-rewired build",
  "test": "react-app-rewired test",
  "eject": "react-scripts eject"
}
  1. 项目根目录新建config-overrides.js文件,添加以下配置:
module.exports = function override(config) {
  config.ignoreWarnings = [
    {
      module: /pdf-parse/,
      message: /Critical dependency: require function is used in a way in which dependencies cannot be statically extracted/
    }
  ]
  return config
}

重新运行npm start即可消除相关警告。

内容的提问来源于stack exchange,提问作者CHeritage

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 00:06:02