项目场景:
前端实现pdf在线预览功能,后段返回的pdf是文件流的形式
问题描述:
前端已通过vue-pdf实现pdf在线预览功能,且本地测试通过,但通过Jenkins打包后部署在测试环境测试时,发现pdf在线预览功能失效,显示白屏,无法正常显示内容,查看控制台报缺少worker.js 404。
报错:GET http://XXX.XXX.XXX.com:8090/c52a93e....worker.js 404(Not Found)
关于如何实现pdf在线预览功能可参考我的另外一篇文章
vue开发日记|使用vue-pdf解决文件流展示pdf的问题_业余的达莲娜的博客-CSDN博客vue-pdf 文件流 分页展示https://blog.csdn.net/qq_43292438/article/details/121380623?spm=1001.2014.3001.5501
原因分析:
经分析,缺少worker.js主要是因为本地打包是worker.js默认生成的路径是在dist根目录下,而我在测试环境打包时,只取了dist目录下的static文件,导致生成的worker.js文件没有打进去,因此出现了上述问题。
解决方案:
思路有两个,一个是直接修改jenkins打包时的路径,把原来的dist/ststic换成dist文件;二是修改node_modules依赖并安装patch-package,将生成的补丁包提交到gitlab,发版时需全量发版,这样就可以在打包的时候自动修改worker.js的路径到dist/static目录下。本次主要是采用的第二个,因为项目原因,用第一个会导致文件存放过乱。
1、进入目录 node_modules/worker-loader/dist/index.js 找到const filename = _loaderUtils2.default.interpolateName(this, options.name || '[hash].worker.js', {}
修改为:
const filename = _loaderUtils2.default.interpolateName(this, options.name ||'ststic/js/[hash].worker.js', {}
2、安装patch-package
npm i patch-package3、创建补丁
运行以下命令
npx patch-package worker-loader
运行后会在项目根目录下的patches目录中创建一个名为worker-loader+2.0.0.patch的文件。然后添加如下代码,即可在打包时自动修node_modules/worker-loader/dist/index.js 的代码。最后将该patch文件提交后,即可在之后应用该补丁了。
diff --git a/node_modules/worker-loader/dist/index.js b/node_modules/worker-loader/dist/index.js
index 7adb3b7..f0a15d9 100644
--- a/node_modules/worker-loader/dist/index.js
+++ b/node_modules/worker-loader/dist/index.js
@@ -67,7 +67,7 @@ function pitch(request) {
const cb = this.async();
- const filename = _loaderUtils2.default.interpolateName(this, options.name || '[hash].worker.js', {
+ const filename = _loaderUtils2.default.interpolateName(this, options.name || 'static/js/[hash].worker.js', {
context: options.context || this.rootContext || this.options.context,
regExp: options.regExp
});
4、在 package.json 的 scripts 中加入
"scripts": {
"postinstall": "patch-package"
}
5、后续再执行 npm install 命令时,会自动为依赖包打补丁了
补充
关于patch-package补丁主要参考的是下面这个博主的
vue-pdf问题解决及patch-package简介 - 简书问题背景 vue中使用vue-pdf打包之后预览报错hash+worker.js路径不对404 解决方式 修改node_modules依赖并安装patch-package,将...https://www.jianshu.com/p/d1887e02f8d6
之前也看了这个博主的解决方案,但是实际并没有效果,因为node_modules的依赖是在npm install的时候自动生成的,修改也只是本地修改,实际是提交不到gitLabvue-pdf生产环境找不到worker.js报错_AngelQ-CSDN博客1:问题描述项目中有预览pdf的功能,在本地测试时,pdf可以正常显示。vuecli打包后,pdf显示白屏,并且报错worker.js404。2:解决查找解决办法,1)修改vue-pdf依赖项依赖里面vue-pdf文件夹下vuePdfNosss.vue


