首页 > 解决方案 > react-pdf 意外令牌生产构建

问题描述

我在 react-pdf 的生产版本中遇到了一些问题。我正在开发的应用程序在使用 webpack-dev-server 构建时运行良好,但是在使用生产 webpack 构建应用程序时,react-pdf 的工作人员无法正常工作。Uncaught SyntaxError: Unexpected token '<'at有一个错误dist1.bundle.js:1

从我在网上发现的情况来看,这表明该工人没有被使用。当我使用 react-pdf 的 github 示例通过 cdn 设置 workerSrc 时,一切都按预期使用 prod 和 dev 构建:

pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`

这告诉我 webpack prod 构建没有找到我的工人的路径,但我不知道为什么它没有找到它。

我还尝试将 pdf.worker.js 文件放在我的组件所在的同一文件夹下的 src 中,我尝试下载 cdn 文件并将其放在 src 中,但这些都没有解决问题。

进口和workerSrc

import { Document, Page, pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = 'node_modules/pdfjs-dist/build/pdf.worker.js';

反应组件:

const Item = (props) => {
  const itemName = props.match.params.itemname;
  const pageTitle = itemName;

  const file = props.location.state.url;
  const type = props.location.state.type;

  const [state, setState] = useState({
    numPages: 0
  });

  const onError = (e) => {
    alert(e, 'error in file-viewer');
  }

  const onDocumentLoadSuccess = ({ numPages }) => {
    setState({ numPages });
  }

  return (
    <>
    <PageHeader pageTitle={pageTitle}/>
      <div className="container-padding">
        {type === 'pdf' ?
         <Document
            file={file}
            onLoadSuccess={onDocumentLoadSuccess}
          >
            {[...Array(state.numPages).keys()].map((page) => (
              <Page pageNumber={page + 1} key={page + 1} />
            ))}
         </Document> 
        :type === 'video'? 
        <video 
          controls
          key="video"
          autoPlay
          playsInline
          src={file}
          onError={onError}>
        </video> : 'No file specified'}
      </div>     
      <br />
    </>
  );

}

标签: javascriptreactjswebpackreact-pdf

解决方案


推荐阅读