我在react-pdf的生产版本中遇到了一些麻烦。当我使用webpack-dev-server构建应用程序时,我正在使用的应用程序运行良好,但是使用生产Webpack构建应用程序时,react-pdf的工作程序无法正常运行。 Uncaught SyntaxError: Unexpected token '<'
处的错误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产品构建找不到我的工作人员的路径,但是我不知道为什么找不到它。
我还尝试将pdf.worker.js文件放在src中与组件相同的文件夹下,并且尝试下载cdn文件并将其放在src中,但是这些都没有解决问题。
import和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 />
</>
);
}