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

react-pdf安装后报错:Module parse failed: Unexpected character '#' 求助

解决react-pdf "Module parse failed: Unexpected character '#'" 报错

这个报错一般是打包工具无法解析react-pdf依赖中的特殊语法(比如JS私有字段#),或者缺少必要的loader配置导致的,以下是几种可行的解决方式:

  • 检查版本兼容性
    确保react-pdf版本和你的React版本匹配。如果用的是React 17及以下,尝试降级react-pdf到v6.x版本:

    npm uninstall react-pdf
    npm install react-pdf@6.2.2
    
  • 添加必要的loader配置
    你的打包工具需要能处理PDF文件和react-pdf依赖的worker脚本:

    1. 先安装依赖:
      npm install worker-loader file-loader --save-dev
      
    2. 修改webpack配置(webpack.config.js):
      module.exports = {
        module: {
          rules: [
            {
              test: /\.pdf$/,
              use: [{ loader: 'file-loader', options: { name: '[name].[ext]' } }]
            },
            {
              test: /pdfjs-dist\/build\/pdf\.worker\.js$/,
              use: { loader: 'worker-loader' }
            }
          ]
        }
      }
      

    如果你用的是Create React App,需要用craco或react-app-rewired修改配置,比如创建craco.config.js:

    module.exports = {
      webpack: {
        configure: config => {
          config.module.rules.push(
            { test: /\.pdf$/, use: [{ loader: 'file-loader' }] },
            { test: /pdfjs-dist\/build\/pdf\.worker\.js$/, use: { loader: 'worker-loader' } }
          );
          return config;
        }
      }
    }
    
  • 修复Babel解析问题
    如果报错是因为JS私有字段#无法被Babel解析,安装对应的插件:

    npm install @babel/plugin-proposal-private-property-in-object --save-dev
    

    然后在babel配置文件(.babelrc或babel.config.json)中添加:

    {
      "plugins": ["@babel/plugin-proposal-private-property-in-object"]
    }
    
  • 修改react-pdf导入方式
    尝试使用指定的入口文件导入:

    import { Document, Page } from 'react-pdf/dist/esm/entry.webpack';
    

最后,清理缓存并重新安装依赖:

rm -rf node_modules package-lock.json
npm install
npm start

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 01:15:37