使用vue-pdf打包后一部分文件部署在cdn上报错的问题(worker-loader)

666 阅读2分钟

问题根源

image.png

可操作的部分

  1. worker-loader/index.js 不建议改这个,它打包出来的文件需要和index.html同一个服务器才能正常加载(同源)
  //决定打包后文件路径 在根目录的js文件夹下 (打包后js文件对该js文件的索引是 publicPath+filename) 
 const filename = _loaderUtils2.default.interpolateName(this, options.name || 'js/[hash].worker.js', {
    context: options.context || this.rootContext || this.options.context,
    regExp: options.regExp
  });
  1. worker-loader/dist/workers/index.js
 // const publicPath = options.publicPath ? JSON.stringify(options.publicPath) : '__webpack_public_path__';
 //由于dist里的index.js filename改为 '/js'纳入js包内,最终索引路径会合成为 ./js/xxx.worker.js  
  const publicPath = '"./"'

传统模式(打包后放在一个服务器上)(该方案可行)

核心配置

  1. vue.config.js publicPath:'./'
  2. worker-loader/index.js js/[hash].worker.js
  3. worker-loader/dist/workers/index.js const publicPath = '"./"'
  • 配置后两个是为了xxx.worker.js能打包进js文件夹里 3也可以不用改,默认套用vue.config.js的publicPath

image.png

image.png

  • 打包后直接部署就能用

修改worker-loader前的打包

image.png

vue.config.js publicPath: "http://47.97.202.171/static/",

image.png

image.png

image.png

image.png

  • 安装vue-pdf时,会同时安装worker-loader,查看node_modules里的包可以看出,如果按worker-loader的默认配置,它打包后,使js里索引该文件也基于webpack的publicpath。由于打包后这个xx.worker.js是在根目录,没部署到cdn服务器,此处这个报错找不到这个文件很正常
  • const publicPath = options.publicPath ? JSON.stringify(options.publicPath) : '__webpack_public_path__';

试着打包进js文件夹,再次部署

  1. vue.config.js publicPath: "http://47.97.202.171/static/"
  2. worker-loader/index.js js/[hash].worker.js
  3. worker-loader/dist/workers/index.js publicPath 不改,还是原文件(套用vue.config.js配置)

image.png image.png

  • 发现即使路径没问题,依旧会报错。
  • 可见html引入一个js的cdn链接,这个js又通过cdn引入另一个js,这种情况对于worker初始化来说是不允许的(待会儿测试js引入另一个js可行性)

修改publicPath,css/js/img部署到cdn、根目录其它文件部署到web服务器(该方案可行)

  1. vue.config.js publicPath: "http://47.97.202.171/static/"
  2. worker-loader/index.js [hash].worker.js
  3. worker-loader/dist/workers/index.js const publicPath = '"./"'

image.png

image.png

  • 打开网页,index.html里引入图二那个js,图二的js到浏览器后 相当于是在index.html里,里面索引的./会相对于当前网页的部署路径(即相对于index.html的位置)再接着引入xxx.worker.js

测试html引入cdn js文件,该cdnjs文件再引入cdnjs文件可行性

前面是html引入cdn js文件,cdn js文件又引入js文件,引入的路径是./ 即相对于index.html位置的js文件 没有问题

此处作为对比

image.png

网上找的方法,通过这种方式引入的js文件内,引入另一个js文件(确实有效,不过和前面那种引入不一样,暂时无法找到合适的对比案例)
var JSElement = document.createElement("script");
JSElement.setAttribute("type", "text/javascript");
JSElement.setAttribute("src", "http://47.97.202.171/static/js/hello.js");
document.body.appendChild(JSElement);