How can I use a vendor libary (specifically I want to use PDF.js) in a Vue component? (I only want to load it for this specific component as they are rather larger files)
I'm building an editor that needs to load a pdf. So I placed the pdf.js and pdf.worker.js in /src/assets/vendor/pdfjs
Then I load both in the template-editor-page.hbs that also loads the component:
<div class="content">
<div class="row fill">
<div class="col-md-2 fill br pt30">
</div>
<div class="col-md-10 fill pt30 pl30 pr30">
<div id="template-editor" class="template-editor">
<template-editor template-src="{{template.src}}"></template-editor>
</div>
</div>
</div>
</div>
<script src="/assets/js/template-editor.bundle.js"></script>
<script src="/assets/vendor/pdfjs/pdf.js"></script>
<script src="/assets/vendor/pdfjs/pdf.worker.js"></script>
my template-editor.js (do I have to load it here?):
import Vue from 'vue';
import templateEditor from './components/template-editor.vue';
new Vue({
el: '#template-editor',
components: { templateEditor }
});
Now I want to load the file in my template-editor.vue:
<template>
<!-- ... -->
</template>
<script>
export default {
props: ['templateSrc'],
name: 'template-editor',
data() {
return {
src: this.templateSrc
};
},
methods: {
render() {
PDFJS.getDocument(this.$data.src).then(function(pdf) {
console.log(pdf);
}, err => console.log(err));
}
},
created: function() {
this.render();
}
};
</script>
But I get an error saying
ReferenceError: PDFJS is not defined
Everything else seems to be working out fine. What am I missing?
I think all that's missing is an import statement in your component,
CORRECTION Try with an '@' in the import location below. I forgot, your component is probably in a sub-folder of 'src'. Also see note below about pdfjs-dist.
Alternative
Since you have webpack, you might be better off installing pdfjs-dist into node modules (see pdfjs-dist), and removing it from './assets/vendor/pdfjs/pdj.js'
If you do this, the import is more 'standard',
Instead of
script
tags for your vendor scripts, better use webpacks dynamic import feature (https://webpack.js.org/guides/code-splitting/#dynamic-imports) to load this vendor library in your render function:For
import
to work you will also have to install this babel plugin http://babeljs.io/docs/plugins/syntax-dynamic-import/.Thank's for your help guys. Turns out the answer was hidden in the first snippet: I import the pdfjs AFTER the bundle. But since the bundle needs it, I need to import it BEFORE:
Really not all that complicated after all ;)